SqlDataSource中的可选列值

时间:2013-09-23 18:28:43

标签: c# asp.net xaml sqldatasource

我有SqlDataSource

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConflictDetection="CompareAllValues"
    ConnectionString="<%$ ConnectionStrings:OracleXexdb %>" 
    ProviderName="<%$ ConnectionStrings:OracleXexdb.ProviderName %>"
    SelectCommand="select col1, col2, col3 from table where col1 < 2000 and (col2 = :col2 OR :col2 is null)"
     OnSelecting="SqlDataSource1_Selecting"
    >
    <SelectParameters>
        <asp:ControlParameter ControlID="codagent" Name="col2" PropertyName="Text" Type="String" ConvertEmptyStringToNull="true" DefaultValue=""/>
    </SelectParameters>
</asp:SqlDataSource>

codagent<asp:TextBox>,用户可以放置值或不放任何内容(“”),如果用户没有任何内容,SqlDataSource不会检索任何值。我的目标是允许用户获取所有col2值,而不使用过滤器

我错过了什么吗?

4 个答案:

答案 0 :(得分:1)

尝试将SQL更改为此类

SelectCommand="select col1, col2, col3 from table where col1 < 2000 and (col2 = :col2 OR  (:col2 is null AND 1=1)"

我不确定Oracle中是否可以使用这些表达式,因为我没有任何使用它的经验,但这是用于在SQL Server中完成相同操作的逻辑。

答案 1 :(得分:1)

由于您已使用SqlDataSource OnSelecting 事件,请使用此事件修改Select命令。

此外,由于您希望用户检索所有col2值,因此实际上只会检索col1<2000的所有此类列。 [表示,可以有col2个值对应于哪个col1&gt; 2000年,所以col2根本不会显示

protected void SqlDataSource1_Selecting(object sender, 
SqlDataSourceSelectingEventArgs e) 
{ 
    if(string.IsNullOrEmpty(codagent.Text))
    {
      e.Command="select col1, col2, col3 from table where col1 < 2000";
    }
}

答案 2 :(得分:1)

我找到了这样做的方法:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConflictDetection="CompareAllValues"
    ConnectionString="<%$ ConnectionStrings:OracleXexdb %>" 
    ProviderName="<%$ ConnectionStrings:OracleXexdb.ProviderName %>"
    SelectCommand="select col1, col2, col3 from table where col1 < 2000 and (col2 = :col2 OR (:col2 is null))"
    >

    <SelectParameters>
        <asp:ControlParameter ControlID="codagent" Name="col2" PropertyName="Text" Type="String" ConvertEmptyStringToNull="false" DefaultValue=""/>
    </SelectParameters>

</asp:SqlDataSource>

这很好用

答案 3 :(得分:0)

为什么不使用子查询。以下代码给出col2,col3 col1是否为空。

select (select col1 from table1 where col1 ='') as col1, col2, col3 from table1