Click here to Skip to main content
15,892,059 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a windows form grid that BindingList<myobj> has set as the datasource. Now I want to filter the data in the grid according to the given condition by the user. This list can have columns like ItemCode, Name, Price. If user says ItemCode="aa" or Name ="bb" how can I dynamically create the LINQ and filter the grid.
Posted

I assume your user will enter Name=aa or ItemCode=bb etc in that format. In that case you would need to split the entry into it's 2 parts using something like this:-

C#
string[] searchArray = txtNameSearch.Text.Split(new char[] { '=' });


you could then use a switch statement to call a method that takes a Predicate<> as a parameter and pass in a lambda expression when you call it, something like this:-

C#
private void Filter(Predicate<myClass> filter)
       {
           List<myClass> filteredClassList = (from myclass in myClassList where filter(myclass) select myclass).ToList();
           dgMyClass.DataContext = filteredClassList;
       }


C#
switch (searchArray[0])
           {
               case "Name":
                   Filter(myclass => myclass.Name.Contains(searchArray[1]) == true);
                   break;
               case "ItemCode":
                   Filter(myclass => myclass.ItemCode.Contains(searchArray[1]) == true);
                   break;
                   //etc
           }


I used a WPF form and DataGrid to test this but it would be the same for a WinForms project, just change DataContext to DataSource

Hope this helps
 
Share this answer
 
 
Share this answer
 
Comments
Nagy Vilmos 5-May-11 7:00am    
Explain.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900