Reputation: 63
I have a DataTable which has columns generated upon a page load. As I do not wish for this table to be re-created every time a postback occurs, I have it in a no-postback if statement. To wit:
DataTable purchase_display_data = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataColumn rownumber = new DataColumn();
rownumber.DataType = System.Type.GetType("System.Int16");
rownumber.AutoIncrement = true;
rownumber.AutoIncrementSeed = 1;
rownumber.AutoIncrementStep = 1;
purchase_display_data.Columns.Add(rownumber);
purchase_display_data.Columns.Add("Item");
purchase_display_data.Columns.Add("Charge");
}
}
Later, I'm attempting to add data after pressing a button. With:
protected void buttonOK_Click(object sender, EventArgs e)
{
DataRow newline = purchase_display_data.NewRow();
newline[1] = "1";
newline[2] = "2";
purchase_display_data.Rows.Add(newline);
}
Upon pressing said button, I return an error stating that the column wasn't found. In debug, I notice that my DataTable has zero columns, despite having created them successfully upon page load (per debug and other testing). The columns seem to have simply vanished. Can somebody tell me why this is occurring and, of course, how to fix it.
Upvotes: 3
Views: 783
Reputation: 5269
You lose your data on postbacks. That's normal. You have to use some of state management mechanisms like ViewState
or Session
to mention few.
You can try this using ViewState
:
private DataTable purchase_display_data
{
get
{
if (ViewState["purchase_display_data"] == null)
ViewState["purchase_display_data"] = new DataTable();
return (DataTable)ViewState["purchase_display_data"];
}
set { ViewState["purchase_display_data"] = value; }
}
Upvotes: 4