开发者

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); , saying the column does not exist. All the rows and columns from the datatable are lost from the datatable when the selectedIndexChanged is executed. 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 dat开发者_开发问答atable everything there is a post back? If I have a class variable of string that doesnt become empty after a postback or does it.


Remove the if (!IsPostBack) .... You have to populate the datatable dt everytime you postback since you aren't storing it anywhere in viewstate or session....


You are adding the columns programmatically in your Page_Load event. The SelectedIndexChanged event causes a postback, and your logic in the Page_Load only adds the columns when the request is NOT a postback. 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. You should get rid of this condition or populate your datatable in another place (maby even your eventhandler for indexchanged event).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜