GridView绑定数据分为两种,一种是多值绑定,另一种是字段绑定。
多值绑定(直接绑定到数据源就行,不需要使用字段):
前台代码:
1 <asp:GridView ID="GridView1" runat="server" width="20% " BackColor="White" BorderColor="White" 2 BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None" > 3 <FooterStyle BackColor="#C6C3C6" ForeColor="Black" /> 4 <RowStyle BackColor="#DEDFDE" ForeColor="Black" /> 5 <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" /> 6 </asp:GridView>
*其中太多的代码,是对控件进行美化。没有其它的改变。
后台代码:
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString; 4 5 SqlConnection connection = new SqlConnection(connectionString); 6 7 connection.Open(); 8 9 string sql = "select * from KK"; 10 11 SqlCommand cmd = new SqlCommand(sql, connection); 12 13 SqlDataReader sdr = cmd.ExecuteReader(); 14 15 GridView1.DataSource = sdr; 16 17 GridView1.DataBind(); 18 19 sdr.Close(); 20 21 connection.Close(); 22 }
最终效果:
-------------------------------------------------------------------------
字段绑定(使用字段):
前台代码:
1 <asp:GridView ID="GridView1" runat="server" width="20% " BackColor="White" BorderColor="White" 2 BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None" 3 AutoGenerateColumns ="false"> 4 <FooterStyle BackColor="#C6C3C6" ForeColor="Black" /> 5 <RowStyle BackColor="#DEDFDE" ForeColor="Black" /> 6 <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" /> 7 <Columns> 8 <asp:BoundField DataField ="id" HeaderText ="编号"/> 9 <asp:BoundField DataField ="name" HeaderText ="姓名"/> 10 </Columns> 11 </asp:GridView>
*要设置AutoGenerateColumns ="false",意思是关闭自动生成列。
后台代码(与多值绑定的后台代码一样):
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString; 4 5 SqlConnection connection = new SqlConnection(connectionString); 6 7 connection.Open(); 8 9 string sql = "select * from KK"; 10 11 SqlCommand cmd = new SqlCommand(sql, connection); 12 13 SqlDataReader sdr = cmd.ExecuteReader(); 14 15 GridView1.DataSource = sdr; 16 17 GridView1.DataBind(); 18 19 sdr.Close(); 20 21 connection.Close(); 22 }
最终效果
如果AutoGenerateColumns ="true"(如果设置自动生成列):
如果AutoGenerateColumns ="false"(如果不设置自动生成列):
以上是GridView的第一版本。
原文:http://www.cnblogs.com/KTblog/p/4273652.html