Quick way to Filter data in GridView Control in ASP.NET
Introduction
In this post we are going to cover following points:
(i) Binding tabular data to a GridView control using the
SqlDataSource control
(ii) Filtering the data using quick method
(iii) 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">
<asp:ListItem>name</asp:ListItem>
<asp:ListItem>address</asp:ListItem>
<asp:ListItem>mobile</asp:ListItem>
</asp:DropDownList>
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.Clear();
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 filtering
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 filtering address or mobile too.
Comments
Post a Comment