We shall see, how to implement
a Client side GridView Filter using LINQ, without hitting the database.
We will be using a C# List as the data source to the Grid View, instead we can
also use a DataTable.
lstCountry.Add(new clsCountry("USA", "United
States"));
lstCountry.Add(new clsCountry("UK", "United
Kingdon"));
lstCountry.Add(new clsCountry("IND", "India"));
grdCountry.DataSource = lstCountry;
Now this will bind all the value to the GridView, to filter the values we need to add a LINQ filter and bind the filtered values to the GridView, as follows
What is LINQ?
To know more about binding a C#
List to a GridView refer the post Binding a C# List to a GridView control
First let us create a class
whose objects will be stored in the List (refer post Binding a C# List to a GridView control)
Next, let us create a list of
objects based on our class clsCountry and
store them in a List object. Here is the code for
the List
List<clsCountry>
lstCountry = new List<clsCountry>();
lstCountry.Add(new
clsCountry("RUS",
"Russia"));
lstCountry.Add(new
clsCountry("SA",
"South Africa"));
lstCountry.Add(new clsCountry("AUS",
"Australia"));
Finally we shall bind the List object
lstCountry to a GridView control. Here the code to bind the
data.
grdCountry.DataSource = lstCountry;
grdCountry.DataBind();
Now this will bind all the value to the GridView, to filter the values we need to add a LINQ filter and bind the filtered values to the GridView, as follows
var filteredCountries = from c in lstCountry
where
c.CountryName.Contains(txtFilter.Text)
select c;
grdCountry.DataSource =
filteredCountries;
grdCountry.DataBind();
Here the LINQ expression takes the filter text from the textbox
txtFilter.Text, and applies the filter on the List object, the result of the
filter expression in bound to the GridView.
In this example we have used a List object, instead we can also use a
DataTable and apply the LINQ filter to the
DataTable.
That’s it we have filtered the contents
of GridView control using LINQ filters.
Related Post
Binding a C# List to a GridView controlWhat is LINQ?
1 comment:
Filter Grid data for GridView
Post a Comment