asp.net 中使用不同的数据源绑定gridview

时间:2022-05-08 11:46:00

第一种,使用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[]);
Response.Write(test3[]);
}
}

读取datatable中的数据,代码如下:

       protected void Page_Load(object sender, EventArgs e)
{ DataTable test2 = binddata();
for (int i = ; i < test2.Rows.Count; i++)
{
Response.Write(test2.Rows[i][]);
} }

读取dataset中的数据,代码如下:

      protected void Page_Load(object sender, EventArgs e)
{
DataSet test1 = binddata1();
for (int i=; i <test1.Tables[].Rows.Count; i++)
{
Response.Write(test1.Tables[].Rows[i][]);
Response.Write(test1.Tables[].Rows[i][]); }
}

仅以此来怀恋一下。