SQL 数据源
可以与数据绑定的控件可以使用 SqlDataSource
控件。SqlDataSource
控件不仅允许你从数据库中检索数据,还可以编辑和排序数据。
检索数据
存储过程:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="sp_GetEmployees"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
SQL 查询:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT
EmployeeID,
EmployeeFirstName,
EmployeeLastName
FROM
dbo.Employees">
</asp:SqlDataSource>
参数:
<asp:SqlDataSource ID="SqlDataSourceEmployees"
runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="SELECT
EmployeeID,
EmployeeFirstName,
EmployeeLastName
FROM
dbo.Employees
WHERE
DepartmentID = @DepartmentID;">
<SelectParameters>
<asp:ControlParameter ControlID="ddlDepartment"
Name="DepartmentID"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
请注意 CancelSelectOnNullParameter
选项,如果设置为 true(默认值),则在任何参数为 NULL 时将停止数据绑定
基本用法
网格视图:
<asp:GridView ID="GridViewEmployees"
runat="server"
AutoGenerateColumns="false"
DataSourceID="SqlDataSourceEmployees">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="Employee ID" />
<asp:BoundField DataField="EmployeeFirstName" HeaderText="First Name" />
<asp:BoundField DataField="EmployeeLastName" HeaderText="Last Name" />
</Columns>
</asp:GridView>