0

我有一个带有旧数据网格的简单 ASP.net 页面。当用户单击按钮时,会运行一个 select 语句并将数据绑定到网格。问题是页面加载后,屏幕只是挂起。表中只有 1 条记录。

ASP页面

<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();
   }
4

2 回答 2

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();
   }
于 2012-06-25T03:16:46.000 回答
0

分配 DataSource 后是否需要调用 mygrid.DataBind()?它可能不会挂。它可能只是没有显示带有数据绑定的网格。

于 2012-06-25T02:26:25.050 回答