简体   繁体   中英

asp.net SqlDataSource FilterExpression empty string logic

here's the logic i want to perform.

When the textbox is empty, i want the datagrid showing no record.
When the textbox is not empty, then the datagrid will filter the data.

Right now, when the textbox is empty, it shows all the records.

How can i fix that? Thanks in advance!

here's the code block:

<asp:SqlDataSource ID="dsGridview" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
    SelectCommand="SELECT UserName, gender, age FROM users"
    FilterExpression="UserName like '%{0}%'">
    <FilterParameters>
        <asp:ControlParameter Name="UserName" ControlID="txtSearch" PropertyName="Text" />
    </FilterParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="dsGridview" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
    SelectCommand="SELECT UserName, gender, age FROM users
                   UserName like '%' +@UserName + '%' and @UserName is not null">
    <SelectParameters>
        <asp:ControlParameter Name="UserName" ControlID="txtSearch" PropertyName="Text" />
    </SelectParameters>
</asp:SqlDataSource>

I noticed FilterExpression behaves a little different (it wraps the parameter name or value with brackets, actually it does SQL escaping), so to check @UserName for null it works with SelectParameters.

Just use a RequiredFieldValidator on txtSearch or on the server side use the below check where appropriate. No need to run a query when you don't want any data returned:

if(String.IsNullOrEmpty(txtSearch.Text))
{
    //don't databind and use validation to tell the user to enter data
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM