ASP.NET SqlDataSource,就像在SelectCommand上一样

时间:2013-04-09 04:04:59

标签: asp.net sql sqldatasource

我正在使用asp.net。我有一个SqlDataSource在selectcommand上硬编码的查询:

<asp:SqlDataSource ID="DataSource1" runat="server" CancelSelectOnNullParameter="False"
    ConnectionString="<%$ ConnectionStrings:S.Properties.Settings.ConnectionString %>" 
    SelectCommand="SELECT * FROM [table]
    WHERE ([col1] like Case @col1_param When null Then col1 Else @col1_param End)
    and  ([col2] like Case @col2_param When null Then col2 Else @col2_param End)"
    SelectCommandType="Text">
    <SelectParameters>
        <asp:ControlParameter ControlID="TextBox1" Name="col1_param" PropertyName="Text"
            Type="String" />
        <asp:ControlParameter ControlID="TextBox2" Name="col2_param" PropertyName="Text"
            Type="String" />
    </SelectParameters>

我想要的是,如果仅在一个文本框中输入数据,则数据将仅根据where子句的文本框值显示。如果没有为这两个文本框都放置任何值,则查询将执行,就好像没有where。

现在使用此代码,如果您只放置一个文本框,则不会显示任何数据。如果所有文本框都为空,则相同。

我不想使用sql存储过程。

我该如何解决这个问题?

...谢谢

2 个答案:

答案 0 :(得分:1)

假设在没有输入文本时它传递null,否则你需要检查空字符串

SelectCommand="SELECT * FROM [table]
    WHERE ([col1] like '%@col1_param%' or @col1_param is null)
    and  ([col2] like '%@col2_param%' or @col2_param is null)"

答案 1 :(得分:0)

听起来您希望查询可选择搜索列。

您可以使用格式

WHERE @col1_param IS NULL OR [col1] LIKE '%@col1_param%'

to property处理未指定参数的情况。

请参阅my question on the issue获取完整答案。当然,它是作为存储过程完成的,但是对于SQLDataSource,概念将保持不变。