简体   繁体   English

数据表列不可访问C#ASP.NET

[英]datatable columns not accessible C# ASP.NET

I have this datatable 我有这个数据表

public partial class class1
{
  private DataTable dt;
  protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
           dt.Columns.Add("Col1", System.Type.GetType("System.String"));
           dt.Columns.Add("Col2", System.Type.GetType("System.String"));
           bind();
        }
    }
}

private void bind()
{
    //database call
    //loop 
    dt.Rows.Add(col1_value.ToString(), col2_value.ToString(), col3.ToString());
    // populate the dropdown list with the database entries
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   DataRow[] datarow;
   variable1=  DropDownList1.SelectedValue;
   datarow = dt.Select( dt.Columns["col1"] + DropDownList1.SelectedValue);
   variable2 = datarow.GetValue(1).ToString();
}

When the selectedindexchange event is called, it displays an error in the line datarow = dt.Select( dt.Columns["col1"] + DropDownList1.SelectedValue); 调用selectedindexchange事件时,它将datarow = dt.Select( dt.Columns["col1"] + DropDownList1.SelectedValue);显示错误datarow = dt.Select( dt.Columns["col1"] + DropDownList1.SelectedValue); , saying the column does not exist. ,表示该列不存在。 All the rows and columns from the datatable are lost from the datatable when the selectedIndexChanged is executed. 执行selectedIndexChanged时,数据表中的所有行和列都将从数据表中丢失。 What am I missing here? 我在这里想念什么?

I want to avoid storing the datatable in session or viewstate. 我想避免将数据表存储在会话或视图状态中。 Also, the question is why does the datatable becomes empty. 另外,问题是为什么数据表会变为空。 Is there anyway to avoid repopulating the datatable everything there is a post back? 无论如何,有没有避免重新填充数据表的所有内容? If I have a class variable of string that doesnt become empty after a postback or does it. 如果我有一个字符串类的类变量,该变量在回发后不会变空或会变空。

删除if (!IsPostBack) ...。每次在回发数据时都必须填充数据表dt,因为您没有将其存储在viewstate或session中的任何位置。

You are adding the columns programmatically in your Page_Load event. 您正在以编程方式在Page_Load事件中添加列。 The SelectedIndexChanged event causes a postback, and your logic in the Page_Load only adds the columns when the request is NOT a postback. SelectedIndexChanged事件导致回发,而Page_Load中的逻辑仅在请求不是回发时才添加列。 This means that the columns are not added back on each postback, which they must be if you want to add them programmatically. 这意味着这些列不会在每次回发中重新添加回去,如果要以编程方式添加它们,则必须将其添加回去。

It may be because of your condition ( if (!IsPostBack) ), indexchanged event causes postback , so columns are never added to the datatable. 可能是由于您的条件( if (!IsPostBack) ), indexchanged事件导致了postback ,所以列永远不会添加到数据表中。 You should get rid of this condition or populate your datatable in another place (maby even your eventhandler for indexchanged event). 您应该摆脱这种情况,或将数据表填充到另一个位置(甚至对于索引更改事件,事件处理程序也可能引起麻烦)。

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

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