我有一个带有旧数据网格的简单ASP.net页面。当用户单击按钮时,select语句将运行并将数据绑定到网格。问题是在页面加载后,屏幕才会挂起。表中只有1条记录。
ASP PAGE
<asp:Button ID="buttonclick" OnClick="clickit" runat="server" Text="GO" />
<asp:DataGrid ID="mygrid" runat="server"
AutoGenerateColumns="true"></asp:DataGrid>
代码背后
public void clickit(Object sender, EventArgs e)
{
string sql = "SELECT a from table1";
SqlConnection connection = new SqlConnection(connectionstring);
SqlDataAdapter adap= new SqlDataAdapter(sql, connection);
DataTable table = new DataTable();
connection.Open();
adap.Fill(table); //page reloads here, but hangs
mygrid.DataSource = table;
connection.Close();
}
答案 0 :(得分:1)
我已经重构了你的代码,现在应该可以了。
public void clickit(Object sender, EventArgs e)
{
//call the function
this.bindGrid();
}
//function to populate the datagrid with the data from the datasource
private void bindGrid()
{
string sql = "SELECT a from table1";
SqlConnection connection = new SqlConnection(connectionstring);
SqlDataAdapter adap= new SqlDataAdapter(sql, connection);
DataTable table = new DataTable();
connection.Open();
adap.Fill(table); //page reloads here, but hangs
mygrid.DataSource = table;
//bind the control with the data in the datasource
mygrid.DataBind();
connection.Close();
}
答案 1 :(得分:0)
分配DataSource后是否需要调用mygrid.DataBind()?它可能不会挂起。它可能只是不显示带有数据绑定的网格。