ASP.NET - storing data in viewstate? - Asked By saranya on 21-Feb-13 09:36 AM

Hi frndz!

i am doing project in asp.net4.0,c#. In my project i am using listview . In listview adding a dynamic rows. The first row inserted successfully. when iam trying to add second row  it inserted successfully but the first row will be(when postback occurs) cleared,so for that problem i can use the viewstate property. the problem will be solved. At the same time one or more users adding rows to listview the values are clashed. Below is my code :

In ADD button click

table = (DataTable)ViewState["table1"];
table.Columns.Add("Gold", typeof(string));
table.Columns.Add("Purity", typeof(string));
table.Columns.Add("Agold", typeof(string));
dr = table.NewRow();
dr["Gold"] = TxtGold.Text;
dr["Purity"] = TxtPurity.Text;
dr["Agold"] = TxtAgold.Text;
table.Rows.Add(dr);
int count = table.Rows.Count;
TotGold = 0.0;
TotAgold =0.0;
for (int i = 0; i < count; i++)
{
TotGold = TotGold + Convert.ToDouble(table.Rows[i]["Gold"].ToString());
TotAgold = TotAgold + Convert.ToDouble(table.Rows[i]["Agold"].ToString());
}
ListView2.DataSource = table;
ListView2.DataBind();
ViewState["table1"] = table;

Here is we adding a row dynamically in listview





Iam in urgent need to complete help me frndz. Thanks in advance!
abdul rehman replied to saranya on 22-Feb-13 02:10 AM

are you looking like this




public partial class JSValuetocs : System.Web.UI.Page


{



DataTable dt;




DataRow dr;




protected void Page_Load(object sender, EventArgs e)


{



if (!IsPostBack)


{

Listview1.DataSource = dt;

Listview1.DataBind();

}

}



protected void Listview1_ItemCommand(object sender, ListViewCommandEventArgs e)


{



if (e.CommandName == "I")


{



TextBox id = (TextBox)e.Item.FindControl("didTextBox");




TextBox name = (TextBox)e.Item.FindControl("dnameTextBox");




TextBox spe = (TextBox)e.Item.FindControl("speTextBox");




if (ViewState["table"] != null)


{

dt = (


DataTable)ViewState["table"];


dr = dt.NewRow();

dr[


"did"] = id.Text;


dr[


"dname"] = name.Text;


dr[


"spe"] = spe.Text;


dt.Rows.Add(dr);

}



else


{

dt =


new DataTable();


dt = Table();

dr = dt.NewRow();

dr[


"did"] = id.Text;


dr[


"dname"] = name.Text;


dr[


"spe"] = spe.Text;


dt.Rows.Add(dr);

}

}

Listview1.DataSource = dt;

Listview1.DataBind();

}



public DataTable Table()


{

dt.Columns.Add(


"did", typeof(int));


dt.Columns.Add(


"dname", typeof(string));


dt.Columns.Add(


"spe", typeof(string));


ViewState[


"table"] = dt;




return dt;


}

}