第一种,使用SqlDataReader绑定gridview。代码如下:
public SqlDataReader bind() { SqlConnection con = new SqlConnection(sqlcon); string sql = "SELECT * FROM test"; SqlCommand cmd = new SqlCommand(sql, con); con.Open(); SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); return dr; }
protected void Page_Load(object sender, EventArgs e) { GridView1.DataSource = bind(); GridView1.DataBind(); }
第二种,使用dataset来绑定gridview。代码如下:
public DataSet binddata1() { DataSet ds = new DataSet(); SqlConnection con = new SqlConnection(sqlcon); string sql = "SELECT * FROM test"; SqlDataAdapter adt = new SqlDataAdapter(sql, con); adt.Fill(ds); return ds; }
protected void Page_Load(object sender, EventArgs e) { GridView1.DataSource = binddata1(); GridView1.DataBind(); }
第三种,使用datatable绑定gridview。代码如下:
public DataTable binddata() { DataTable tt = new DataTable(); SqlConnection con = new SqlConnection(sqlcon); string sql = "SELECT * FROM test"; SqlDataAdapter adt = new SqlDataAdapter(sql, con); adt.Fill(tt); return tt; }
protected void Page_Load(object sender, EventArgs e) { GridView1.DataSource = binddata(); GridView1.DataBind(); }
下面来说一下怎么读取SqlDataReader中的数据。代码如下:
protected void Page_Load(object sender, EventArgs e) { SqlDataReader test3 = bind(); while (test3.Read()) { Response.Write(test3[0]); Response.Write(test3[1]); } }
读取datatable中的数据,代码如下:
protected void Page_Load(object sender, EventArgs e) { DataTable test2 = binddata(); for (int i = 0; i < test2.Rows.Count; i++) { Response.Write(test2.Rows[i][0]); } }
读取dataset中的数据,代码如下:
protected void Page_Load(object sender, EventArgs e) { DataSet test1 = binddata1(); for (int i=0; i <test1.Tables[0].Rows.Count; i++) { Response.Write(test1.Tables[0].Rows[i][0]); Response.Write(test1.Tables[0].Rows[i][1]); } }
仅以此来怀恋一下久。
时间: 2024-10-07 11:34:55