2013-09-23 28 views
4

button_click事件被触发时。我从方法中获得DataTable,并将其分配给在类中定义的DataTable,但是这个设置为DataTable。如果我绑定DataTableGridView它显示数据。DataTable未分配

public partial class Default : System.Web.UI.Page 
{ 
    TestClass test = new TestClass(); 
    DataTable _table = new DataTable(); 

    protected void Button1_Click(object sender, EventArgs e) 
    { 

     _table = test.getTable(); 
    //displaying table 
     GridView1.DataSource= _table; 
     GridView1.DataBind(); 
    } 
    protected void Button2_Click(object sender, EventArgs e) 
    { 
     //does not displaying table 
     GridView2.DataSource= _table; 
     GridView2.DataBind(); 
    } 
} 

当我想从_table得到一些数据时,它什么也没有。怎么了?

更新: 感谢所有,特别是Darren Davies,问题在回发。当Button2_Click事件发生时_table分配_table = new DataTable(),因此_table不再引用由方法getTable()返回的表。

+0

确定getTable()返回数据? –

+0

我调试它和_table哈哈ve行[count = 54],但然后我单击button2行有count = 0. –

+0

@AlbertGore - 最有可能发生回发。你需要再次调用'getTable' –

回答

4

如果在Button2之前单击Button1,它将只能正确绑定。否则_table将不会被填充。

你应该检查_table有数据或致电Button2_Click事件处理程序内的getTable方法:

protected void Button2_Click(object sender, EventArgs e) 
    { 
     _table = test.getTable(); 
     GridView2.DataSource= _table; 
     GridView2.DataBind(); 
    } 
0

什么你可以尝试是这样的:

protected void Button1_Click(object sender, EventArgs e) 
     { 

      _table = test.getTable(); 
     //displaying table 
     GridVieuw1.Datasource = null; 
     GridView1.DataSource= _table; 
     GridView1.DataBind(); 

     } 

你也必须在buuton做到这一点2

protected void Button2_Click(object sender, EventArgs e) 
      { 

       _table = test.getTable(); 
      //displaying table 
      GridVieuw2.Datasource = null; 
      GridView2.DataSource= _table; 
      GridView2.DataBind(); 

      } 

Otheriwse the t能够在按钮2空的,所以你必须按下按钮1来填补它

也许可以做的伎俩

0

要初始化您DataTable

DataTable _table = new DataTable(); 

然后,当你点击你的按钮1:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    _table = test.getTable(); // <- here 
//displaying table 
    GridView1.DataSource= _table; 
    GridView1.DataBind(); 
} 

你分配你的DataTable不同实例。 你必须调试和检查你的方法getTable返回一个有效DataTable(如果你想看到你的数据,请确保它包含的数据。当你不扣2之前按下按钮1

0

您的问题出现你应该广义你的数据像这样绑定:

public partial class Default : System.Web.UI.Page 
{ 
    TestClass test = new TestClass(); 
    DataTable _table = new DataTable(); 

    protected void Button1_Click(object sender, EventArgs e) 
    { 

     FillDataTable(); // <----------- See this function call 

    //displaying table 
     GridView1.DataSource= _table; 
     GridView1.DataBind(); 
    } 
    protected void Button2_Click(object sender, EventArgs e) 
    { 

     FillDataTable(); // <----------- See this function call 

     //does not displaying table 
     GridView2.DataSource= _table; 
     GridView2.DataBind(); 
    } 

    private void FillDataTable() 
    { 
     if(_table.Rows.Count == 0) 
      _table = test.getTable(); 
    } 
} 

这将是明智的方式来填补表一次,而不是填充每按一下按钮,它在每一个按钮单击事件写下