一般來說我們都會將使用codebehind的方式來指定SqlDataSource的SelectCommand內容。但在比較複雜的邏輯程式中不得已必須在設計模式中直接指定SelectCommand內容,又需要對某控制項來取值作為SQL中的Where條件時,我們可以使用T-SQL中的條件語法If…Else來實現。
T-SQL If…Else 架構:
If 條件式
Begin
T-SQL語法
End
Else
Begin
T-SQL語法
End
Begin End是用來設定T-SQL程式碼範圍,若你的T-SQL語法超過一行請務必記得加上Begin End,否則你會發現就算寫了多行也只會執行第一行程式。最好是養成不管一行多行程式都用Begin….End包起來的好習慣。
範例:
在SqlDataSource的SelectCommand對DropDownList控制項取值,判斷DropDownList值是否為All來達成不同條件資料過濾。
DropDownList內容:
<asp:DropDownList ID="DropDownList" runat="server"
AppendDataBoundItems="True" DataSourceID="Sort_SqlDataSource"
DataTextField="分類項目" DataValueField="分類編號">
<asp:ListItem Value="All">請選擇</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="Sort_SqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM 分類"></asp:SqlDataSource>
SqlDataSource SelectCommand內容:
<asp:SqlDataSource ID="SqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="if (@分類項目='All') begin Select * From 測試 end else begin Select * From 測試 Where 分類項目=@分類項目 end">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList" Name="分類項目" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
0 意見:
張貼意見