第一種,使用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]); } }
僅以此來懷戀一下。