触发button_click
事件时。我从方法中获取DataTable
并将其分配给课程中定义的DataTable
,但此DataTable
设置为空。如果我将DataTable
绑定到GridView
,则会显示数据。
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,问题出现在Postback中。当Button2_Click事件发生时_table赋予_table = new DataTable(),因此_table不再引用方法getTable()返回的表。
答案 0 :(得分:4)
如果在Button2之前单击Button1,它将只能正确绑定。否则将不会填充_table
。
您应该检查_table
是否有数据,或者调用getTable
事件处理程序中的Button2_Click
方法:
protected void Button2_Click(object sender, EventArgs e)
{
_table = test.getTable();
GridView2.DataSource= _table;
GridView2.DataBind();
}
答案 1 :(得分: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();
}
如果表格在按钮2处为空,则必须按下按钮1才能填写
也许这可以解决问题
答案 2 :(得分: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
(如果您想查看数据,请确保它包含数据。
答案 3 :(得分:0)
如果您没有在按钮2之前按下按钮1,则会出现问题。您应该像这样概括数据绑定:
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();
}
}
填充表格是一种明智的方式,而不是填写每个按钮点击并在每个按钮点击事件中写下来。