Asp SqlDataSource将数据库数据绑定在 GridView
1.首先认识一下GridView的几条属性
☻AllowPaging 确定是否可以分页
☻AllowSorting 确定是否可以进行排序
☻AlternatingRowStyle 指定奇数行样式
☻AutoGenerateColumns 确定是否根据绑定的数据源自动生成对应的列
☻DataSource 指定绑定到控件的数据源
☻DataSourceID 指定绑定到控件的数据源控件的ID
2.关键代码
<body>
<form id="form1" runat="server">
<div>
<h1>实验数据</h1>
</div>
<asp:GridView ID="GridView1" runat="server" Width="823px" AutoGenerateColumns="False" EnableModelValidation="True"
DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True" GridLines="None" BorderColor="Silver"
BorderStyle="Solid" BorderWidth="1px" >
<%--绑定Test数据库的几个属性ID Name Age--%>
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="true" SortExpression="ID">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="true" SortExpression="ID">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Age" HeaderText="Age" ReadOnly="true" SortExpression="ID">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
</Columns>
<RowStyle Height="42px" />
<HeaderStyle BackColor="#33CC33" Height="40px"/>
<AlternatingRowStyle BackColor="#E0E0E0" ForeColor="#003366" BorderColor="Black"
BorderStyle="None" />
</asp:GridView>
<%--连接数据库--%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="Data Source=IP;Initial Catalog=数据库名称;Persist Security Info=True;User ID=**; Password=**"
ProviderName="System.Data.SqlClient" SelectCommand="SELECT [ID], [Name], [Age] FROM [Test]">
</asp:SqlDataSource>
</form>
</body>
浙公网安备 33010602011771号