protected void Button1_Click1(object sender, EventArgs e)
{
SqlConnectionStringBuilder connb = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["SCS"].ConnectionString);
using (SqlConnection conn = new SqlConnection(connb.ConnectionString))
{
SqlCommand cmd = new SqlCommand("Select * from dbo.Users;", conn);
DataTable tb = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
tb.AcceptChanges();
GridView1.DataSource = tb;
GridView1.DataBind();
}
}
这是我在 C# asp.net 应用程序中的代码。我想在 gridview 中显示 SQL 表。
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="name" />
<asp:BoundField ItemStyle-Width="150px" DataField="lastname" HeaderText="lastname" />
<asp:BoundField ItemStyle-Width="150px" DataField="ID" HeaderText="ID" />
</Columns>
IT 显示空 GridView (当我按下按钮 1 时)。它不显示任何错误消息。连接字符串有效,SQL 命令影响行,但它仍然没有在 gridview 上显示任何数据!!!
谁能帮帮我?
最佳答案
您可能会在 DataBind()
中遇到异常 - 使用 try-catch
block 。这可能是由于在绑定(bind)字段中使用的 DataTable
中缺少列。
protected void Button1_Click1(object sender, EventArgs e)
{
SqlConnectionStringBuilder connb = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["SCS"].ConnectionString);
using (SqlConnection conn = new SqlConnection(connb.ConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand("Select * from dbo.Users;", conn);
DataTable tb = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tb);
tb.AcceptChanges();
GridView1.DataSource = tb;
GridView1.DataBind();
GridView1.Rows[0].Cells[0].Text. = "a";
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
}
关于c# - asp.net gridview 不显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20854858/