为什么这段代码没有在浏览器中显示表格?

时间:2015-07-19 16:54:51

标签: c# asp.net datatable sqldatareader

在下面的asp c#代码中,我试图使用SqlDataReader显示数据库表的内容,但它无法正常工作。此代码仅处理按钮单击事件。我怎样才能使它工作?

protected void Button2_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = null;
        GridView1.DataBind();
        string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        using (con)
        {
            con.ConnectionString = CS;
            DataTable dTbl = new DataTable();
            dTbl.Columns.Add("ID");
            dTbl.Columns.Add("Name");
            dTbl.Columns.Add("Salary");
            SqlCommand vmd = new SqlCommand();
            vmd.Connection = con;
            vmd.CommandText = "select * from [dbo].[employee]";
            con.Open();
            SqlDataReader dr = vmd.ExecuteReader();
            while (dr.Read())
            {
                DataRow dRow = dTbl.NewRow();
                dRow["ID"] = dr[0];
                dRow["Name"] = dr[1];
                dRow["Salary"] = dr[2];
                dTbl.Rows.Add(dRow);
            }
        }
    }

2 个答案:

答案 0 :(得分:2)

while代码块添加后

GridView1.DataSource = dTbl;
GridView1.DataBind();

并从您的代码开头删除GridView1.DataBind();

答案 1 :(得分:1)

你不需要这条线。从代码的开头删除它:

GridView1.DataBind();//Remove

然后在While循环后放置这两行:

GridView1.DataSource = dTbl;
GridView1.DataBind();

修改:您也可以这样做更简单:

string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
      try
      {
           con.Open();
           SqlCommand command = new SqlCommand("select * from [dbo].[employee]", con);
           SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
           GridView1.DataSource = reader;
           GridView1.DataBind();
       }
       catch
       {
         //Handle error
       }
}