我是ASP.NET的新手,使用下面的查询来获取SQLDataAdapter中的数据以进行GridView显示。但看起来数据不是在SQLDataAdapter本身中获取的。相同的代码在SQLReader中运行良好。谁能帮助我理解我在这里做错了什么?
SqlConnection conn = new SqlConnection(connectionString);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
String sql = "Select top 100 * from xyz";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet Output = new DataSet();
adapter.Fill(Output, "out");
GridViewOutput.DataSource = Output.Tables["out"];
/* using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Response.Write( reader.GetString(0)+ reader.GetString(2));
}
}
}*/
conn.Close();
你需要打电话 -
GridViewOutput.DataBind()
指定数据源后。
更多关于此 -
你错过了绑定Gridview的行。
SqlConnection conn = new SqlConnection(connectionString);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
String sql = "Select top 100 * from xyz";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet Output = new DataSet();
adapter.Fill(Output, "out");
GridViewOutput.DataSource = Output.Tables["out"];
GridViewOutputData.DataBind();
/* using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Response.Write( reader.GetString(0)+ reader.GetString(2));
}
}
}*/
conn.Close();
设置数据源后,您忘记包含DataBind()
方法。 GridView
数据绑定的正确方法应该是这样的:
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet output = new DataSet();
adapter.Fill(Output, "out");
GridViewOutput.DataSource = Output; // bind directly to DataSet
GridViewOutput.DataBind(); // bind to grid