我创建了一个Label控件和gridview。 Label显示数据,但在Gridview中,数据库中的数据不会填充。 以下是我的代码。执行此操作时未收到任何错误
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["TestConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select BATSMAN_NAME from RUNS_STATS", con);
con.Open();
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
Label1.Text = dr.GetString(dr.GetOrdinal("BATSMAN_NAME"));
}
GridView2.DataSource = dr;
GridView2.DataBind();
con.Close();
}
}
}
答案 0 :(得分:1)
使用SqlDataAdapter&数据集来填充gridview
SqlCommand cmd = new SqlCommand("Select BATSMAN_NAME from RUNS_STATS", con);
SqlDataAdapter daGrid = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
daGrid.Fill(ds);
GridView2.DataSource = ds.Tables[0];
GridView2.DataBind();
答案 1 :(得分:0)
尝试断开连接的架构。如果以下代码不起作用,请检查查询是否合适。
SqlConnection conobj=new SqlConnection;
SqlCommand cmdobj=new SqlCommand(""Select BATSMAN_NAME from RUNS_STATS", conobj);
SQlDataAdapter sdaobj=new SqlDataAdapter(cmdobj);
DataTable dtobj=new DataTable();
sdaobj.Fill(dtobj);
GridView2.DataSource=dtobj;
GridView2.DataBind();