| 參數類型 | 來源 | 範例 |
| QueryStringParameter | URL 查詢字串 | <asp:QueryStringParameter Name="CategoryID" QueryStringField="cat" Type="Int32" /> |
| ControlParameter | 頁面控制項屬性 | <asp:ControlParameter Name="Price" ControlID="txtPrice" PropertyName="Text" Type="Decimal" /> |
| SessionParameter | Session 變數 | <asp:SessionParameter Name="UserID" SessionName="UID" Type="Int32" /> |
| ProfileParameter | 使用者設定檔 | <asp:ProfileParameter Name="Theme" PropertyName="Theme" Type="String" /> |
| CookieParameter | Cookie 值 | <asp:CookieParameter Name="Lang" CookieName="Culture" Type="String" /> |
| Parameter | 程式碼手動指定 | 在 Selecting 事件中 e.Command.Parameters["@Price"].Value = 100; |
宣告式範例:依查詢字串篩選產品
<asp:SqlDataSource ID="ProductsDS" runat="server"
ConnectionString="%$ ConnectionStrings:Northwind %$"
SelectCommand="SELECT ProductID, ProductName, UnitPrice FROM Products WHERE CategoryID = @CategoryID">
<SelectParameters>
<asp:QueryStringParameter Name="CategoryID" QueryStringField="cat" Type="Int32" DefaultValue="1" />
</SelectParameters>
</asp:SqlDataSource>
程式化指定參數:Selecting 事件
protected void ProductsDS_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// 依據複雜商務邏輯動態決定參數
if (User.IsInRole("Admin"))
e.Command.Parameters["@CategoryID"].Value = DBNull.Value; // 全部分類
else
e.Command.Parameters["@CategoryID"].Value = GetUserDefaultCategory();
}
多參數組合查詢範例
SelectCommand="SELECT * FROM Products WHERE
(@CategoryID IS NULL OR CategoryID = @CategoryID) AND
(@MinPrice IS NULL OR UnitPrice >= @MinPrice) AND
(@MaxPrice IS NULL OR UnitPrice <= @MaxPrice)"
<SelectParameters>
<asp:QueryStringParameter Name="CategoryID" QueryStringField="cat" Type="Int32" ConvertEmptyStringToNull="true" />
<asp:ControlParameter Name="MinPrice" ControlID="txtMin" PropertyName="Text" Type="Decimal" ConvertEmptyStringToNull="true" />
<asp:ControlParameter Name="MaxPrice" ControlID="txtMax" PropertyName="Text" Type="Decimal" ConvertEmptyStringToNull="true" />
</SelectParameters>
關鍵屬性:ConvertEmptyStringToNull
設為 true 時,空字串自動轉為 NULL,搭配 `IS NULL` 判斷可實現「未輸入即不篩選」效果。
儲存程序參數
同樣支援參數化,參數名稱需與 SP 定義一致 (含 @ 前綴),方向可設 Input/Output/ReturnValue。
- 上一篇文章: ASP.NET 2.0 資料教程 49:SqlDataSource 插入、更新、刪除完整教學
- 下一篇文章: ASP.NET 2.0 資料教程 47:SqlDataSource 基礎查詢與 ObjectDataSource 比較
Copyright ©
程式碼之家 All Rights Reserved