Quick way to Filter data in GridView in ASP.NET SQL Server DB


In this post we are going to cover following points:

  • Binding tabular data to a GridView control using the SqlDataSource control
  • Filtering the data using quick method
  • Focus on imperative code rather than declarative code

I am going to explain it using step by step method so that you can follow it and create the sample application. Follow the steps:

Step 1:

Create the database as its structure given below in screenshot.


Step 2:

Now drag the database table from Server Explorer to form (which should be in design mode), find the screenshot given below.


Step 3:

Now add a DropDownList box and list some item in this. For this you need to create a DropDownList on form in design mode and then select its Items properties this will pop a window which will allow you to add the items for this. You can simply add the items using code as given below.

        <asp:DropDownList ID="DropDownList1" runat="server">


Step 4

When you done with DropDownList, you need to add a TextBox that will accept the textual data to filter records and also you need to add a Button to perform filter task by its click event.


Step 5

Now our design work is over, let's place some code in button click event to filter records. Remember I already have place some records in my database table. Here is the code.

    protected void Button1_Click(object sender, EventArgs e)
string FilterExpression = string.Concat(DropDownList1.SelectedValue, " LIKE '%{0}%'");
SqlDataSource1.FilterParameters.Add(new ControlParameter(DropDownList1.SelectedValue, "TextBox1", "Text"));
SqlDataSource1.FilterExpression = FilterExpression;

When I run the application, I have following records.


Let's filter it by name or address or mobile, I am trying filter records by name by typing just 'o' in text box. It will filter all names contain character 'o'. Here is my output.


In the same way, you can try by address or mobile as well.

I hope you like it. Comments Please.

Up Next
    Ebook Download
    View all
    View all