简体   繁体   中英

Columns in DataTable Disappearing

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM