1

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>

2 Answers 2

1
<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.

Sign up to request clarification or add additional context in comments.

2 Comments

it works like a charm! thanks Adrian. Why the first one didn't work for filterExpression? any good article explaining this?
@JohnnySun, I don't know any article, while testing it I found it does some kind of replacement. So it translates "@UserName is not null" to "[value entered in textbox] is not null"..
0

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
}

1 Comment

i'm using ajax on the aspx page, so it won't go to backend code to check whether the textbox is empty. so when the user type something in the textbox, it refresh the GridView without reload the page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.