I'm new in LINQ so I hope this isn't a stupid question:
I have a table with a lot of content presented in a datagrid, and I want the user to be able to filter the grid by using some combo boxes above the grid [like a search bar]
I created a method that takes the text in the combo boxes, and placing it the "Where" clause:
public void find()
{
string disName;
string statusName;
disName = RMcmbDis.Text; //This Get the first string to filter
statusName = RMcmbStatus.Text; // this get the second string to filter
//Here I gather all the data I need
var allCNT = from x in cntDB.releases
join dis in cntDB.disciplines on x.discipline equals dis.discipline_id
join btch in cntDB.batches on x.batch_num equals btch.batch_id
join z in cntDB.status on x.status equals z.status_id
select new { dis.discipline_name, x.grade, x.batch_num, btch.batch_name, z.status_description, x.segment_leader, x.ped_leader, x.release_location, x.comments, x.QA_Verdict };
//Here I make the filtering
var find = allCNT.Where(a => a.discipline_name == disName && a.status_description == statusName);
dataGridView1.DataSource = find;
}
Now I have a problem: I want the user to be able to leave one of the combo boxes empty and if he does so, this means he doesn't want to filter that criteria. [E.G - The combo "RMcmbDis" has "Math" and the Status combo ["RMcmbStatus"] is empty, so the grid will show only "Math" in all status'.
How Do I do that? Thanks guys... N.
You can just add Where()
clauses if the condition you want is true...
var results = allCNT;
if (!string.IsNullOrEmpty(disName))
results = result.Where(a => a.discipline_name == disname);
if (!string.IsNullOrEmpty(statusName))
results = results.Where(a => a.status_description == statusName);
dataGridView1.DataSource = results;
See comment below for one option for handling lots of filters. Another option is to use a helper method:
T AddFilter<T>(IQueryable<T> results, string filterValue, Expression<Func<T, bool>> predicate)
{
if(!string.IsNullOrEmpty(filterValue))
return results.Where(predicate);
return results;
}
Which you would use like this:
var results = allCNT;
results = AddFilter(results, disname, a => a.discipline_name == disname);
results = AddFilter(results, statusName, a => a.status_description == statusName);
results = AddFilter(results, whatever, a => a.whatever == whatever);
// ...
dataGridView1.DataSource = results;
You can add several Where
clauses depending on what criteria you have, e.g.:
var find = allCNT;
if (!string.IsNullOrEmpty(disName))
{
find = find.Where(a => a.discipline_name == disName);
}
if (!string.IsNullOrEmpty(statusName))
{
find = find.Where(a.status_description == statusName);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With