Columns in DataTable Disappearing

I have a DataTable that has columns generated on page load. Since I don't want this table to be recreated every time a postback occurs, I have it in the 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 try to add data after button click. FROM:

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);
}

      

When I click this button, I get back a message that the column was not found. In debugging, I notice that my DataTable has null columns, even though they were created successfully on page load (for debugging and other testing). It seems that the columns have just disappeared. Can someone tell me why this is happening and of course how to fix it.

+3


source to share


1 answer


You lose your data on postback. This is normal. You have to use some mechanisms of government, such as ViewState

or Session

to mention a 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; }
}

      

+4


source







All Articles