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>