简体   繁体   English

DataTable中的列消失了

[英]Columns in DataTable Disappearing

I have a DataTable which has columns generated upon a page load. 我有一个DataTable,其中包含页面加载时生成的列。 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. 因为我不希望每次发生回发时都重新创建这个表,所以我在no-postback if语句中使用它。 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). 在调试中,我注意到我的DataTable没有列,尽管在页面加载时成功创建了它们(每次调试和其他测试)。 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. 您必须使用一些状态管理机制,如ViewStateSession来提及一些。

You can try this using ViewState : 您可以使用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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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