Click here to Skip to main content
15,884,537 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have the tblEmp which populates my datagridview. I wanna now filter the records depending on two comboboxes.

            tblEmp
FName	LName	Age	City
Mike	Brown	25	Berlin
James	Blue	35	Accra
Philip	Gay	20	London
Simon	Black	15	Berlin
Martin	Adjei	45	London
Peter	Moore	33	Pari
Philip	Gay	51	Berlin		


The first combobox (cb1) is filed with the city names + the string All & 
The second one (cb2) is filled with LNames + the string All.

To filter the dgv based on one combobox is not the problem. 
My Problem is how can i ajust my code so that the filtering takes both comboboxes into consideration?? And if I select All it should then show me again all records in the dgv.

That's my code for the filtering (It's also the same for cb2):


C#
private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
    string showall = cb1.SelectedItem.ToString();
    if (showall == "All")
    {


    }

    else if (cb1.SelectedItem != null)
    {
        //Check an see what's in the dgv
        DataView dv = new DataView(dt);
        // now filter
        dv.RowFilter = " [City] = " + cb1.Text.Trim();
        datgridview1.DataSource = dv;

    }
    else
    {
        MessageBox.Show("No records found");
    }
}


So that's my records if i choose [Berlin] in the cb1 (That' working)

FName	LName	Age	City
Mike	Brown	25	Berlin
Simon	Black	15	Berlin
Philip	Gay	51	Berlin

MY QUESTION: How Can I Get this record when i select [Berlin] in cb1 & [Gay] in cb2?

FName	LName	Age	City
Philip	Gay	51	Berlin

OR [London] & [Adjei]?

FName	LName	Age	City
Martin	Adjei	45	London

OR [All] & [Gay]?



FName	LName	Age	City
Philip	Gay	20	London
Philip	Gay	51	Berlin
Posted
Updated 25-Nov-14 3:50am

1 solution

Hello,

This is very simple. You can use more than one condition in DataView's RowFilter property.

C#
private DataTable _dt;

public Form1()
{
    InitializeComponent();
}

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    LoadData();
    LoadFilterData();

    FilterData();
}

private void LoadData()
{
    // Create table
    _dt = new DataTable();
    _dt.Columns.Add("FName", typeof(string));
    _dt.Columns.Add("LName", typeof(string));
    _dt.Columns.Add("Age", typeof(int));
    _dt.Columns.Add("City", typeof(string));

    // Fill data
    _dt.Rows.Add("Mike", "Brown", 25, "Berlin");
    _dt.Rows.Add("James", "Blue", 35, "Accra");
    _dt.Rows.Add("Philip", "Gay", 20, "London");
    _dt.Rows.Add("Simon", "Black", 15, "Berlin");
    _dt.Rows.Add("Martin", "Adjei", 45, "London");
    _dt.Rows.Add("Peter", "Moore", 33, "Paris");
    _dt.Rows.Add("Philip", "Gay", 51, "Berlin");
}

private void LoadFilterData()
{
    cb1.Items.AddRange(new string[] { "All", "Berlin", "Accra", "London", "Paris" });
    cb2.Items.AddRange(new string[] { "All", "James", "Martin", "Mike", "Peter", "Philip", "Simon" });
    cb3.Items.AddRange(new string[] { "All", "Brown", "Gay", "Black", "Adjei", "Moore" });
    // Fill age filter comboboxes
    for (int i = 0; i <= 100; i++)
    {
        cbFilterAgeFrom.Items.Add(i);
        cbFilterAgeTo.Items.Add(i);
    }
}

private void cb1_SelectedIndexChanged(object sender, EventArgs e)
{
    FilterData();
}

private void cb2_SelectedIndexChanged(object sender, EventArgs e)
{
    FilterData();
}

private void cb3_SelectedIndexChanged(object sender, EventArgs e)
{
    FilterData();
}

private void cbFilterAgeFrom_SelectedIndexChanged(object sender, EventArgs e)
{
    FilterData();
}

private void cbFilterAgeTo_SelectedIndexChanged(object sender, EventArgs e)
{
    FilterData();
}

private void FilterData()
{
    DataView dv = new DataView(_dt);

    var cityFilter = string.IsNullOrWhiteSpace(cb1.Text) ? "All" : cb1.Text.Trim();
    var fNameFilter = string.IsNullOrWhiteSpace(cb2.Text) ? "All" : cb3.Text.Trim();
    var lNameFilter = string.IsNullOrWhiteSpace(cb3.Text) ? "All" : cb2.Text.Trim();
    // Get values for age filter
    var ageFromFilter = string.IsNullOrWhiteSpace(cbFilterAgeFrom.Text) ? 0 : (int)cbFilterAgeFrom.SelectedItem;
    var ageToFilter = string.IsNullOrWhiteSpace(cbFilterAgeTo.Text) ? 0 : (int)cbFilterAgeTo.SelectedItem;

    // Make list for keeping single filter values
    var filterItems = new List<string>();
    if (cityFilter != "All")
    {
        filterItems.Add(string.Format(" [City] = '{0}'", cityFilter));
    }
    if (fNameFilter != "All")
    {
        filterItems.Add(string.Format(" [FName] = '{0}'", fNameFilter));
    }
    if (lNameFilter != "All")
    {
        filterItems.Add(string.Format(" [LName] = '{0}'", lNameFilter));
    }
    if (ageFromFilter > 0)
    {
        filterItems.Add(string.Format(" [Age] >= {0}", ageFromFilter));
    }
    if (ageToFilter > 0)
    {
        filterItems.Add(string.Format(" [Age] <= {0}", ageToFilter));
    }

    // If there are filter items on the list we will join them into one string
    if (filterItems.Count > 0)
    {
        var filter = string.Join(" AND ", filterItems);
        // You can remove this line, it is just for 'debugging' purposes :)
        MessageBox.Show(filter);
        dv.RowFilter = filter;
    }
    dataGridView1.DataSource = dv;
}


More informations about RowFilter you can find here:
http://www.csharp-examples.net/dataview-rowfilter/[^]

[Update - Answer for comment]
If you have more filter conditions there is a little bit simpler solution than my previous. I think that filtering age is better to filter between two values (from-to) than searching for exact value. So I've modified my answer and you should take some steps:
cb1 -> Combo filter for Cities
cb2 -> Combo filter for First names
cb3 -> Combo filter for Last names
Add two comboboxes for age filtering:
cbFilterAgeFrom, cbFilterAgeTo -> Combo for filter age From-To

Don't forget to bind SelectedIndexChanged event handler for new ComboBoxes.

Little explanation what is going here:
1. We are declaring List<string> to keep filter values for single fields. If you have selected City (i.e. Berlin) and AgeTo (i.e. 27) then our list will contain values like this:
[City] = 'Berlin'
[Age] <= 27

2. At the and of method FilterData we are checking if list contains some items. If yes, then we are joining them to get one string for all filterItems and we are adding 'AND' operator. So finally we get something like this:
[City] = 'Berlin' AND [Age] <= 27

And some links:
String.Join method[^]
Collections in .NET[^]

I hope you will find this useful :)
 
Share this answer
 
v3
Comments
mikybrain1 26-Nov-14 3:08am    
Thnx very much Dude :) Was really a great help.
Marcin Kozub 26-Nov-14 3:09am    
You're welcome :)
mikybrain1 4-Dec-14 8:52am    
Hi Marcin
sorry but i getcha worry u on this. Am trying to expand my filtering by adding two more comboboxes (cb3(age)and cb4(FName)). i have edited the help code u provided me but it isn't working right.

private void FilterData()
{
DataView dv = new DataView(_dt);

string filter = string.Empty;

var cityFilter = string.IsNullOrWhiteSpace(cb1.Text) ? "All" : cb1.Text.Trim();
var nameFilter = string.IsNullOrWhiteSpace(cb2.Text) ? "All" : cb2.Text.Trim();
var ageFilter = string.IsNullOrWhiteSpace(cb3.Text) ? "All" : cb3.Text.Trim();
var fnameFilter = string.IsNullOrWhiteSpace(cb4.Text) ? "All" : cb4.Text.Trim();

if (cityFilter != "All" && nameFilter == "All" && fFilter == "All" && ageFilter == "All")
{
filter = string.Format(" [City] = '{0}'", cityFilter);
}
else if (cityFilter == "All" && nameFilter != "All" && ageFilter == "All" && fnameFilter == "All")
{
filter = string.Format(" [LName] = '{0}'", nameFilter);
}
else if (cityFilter != "All" && nameFilter != "All" && ageFilter == "All" && fnameFilter == "All"))
{
filter = string.Format(" [City] = '{0}' AND [LName] = '{1}' AND [Age] = '{2}' AND [FName] = '{3}'", cityFilter, nameFilter, fnameFilter, ageFilter);
}

if (!string.IsNullOrEmpty(filter))
{
dv.RowFilter = filter;
}
dataGridView1.DataSource = dv;
}

Can u please help me again on that? will apreciate that!!!

something like(Filter): if cb3 = 25, cb2=Brown, cb1= Berlin and cb4 =Mike
Datagridview shld looks like:
Mike Brown 25 Berlin
Marcin Kozub 4-Dec-14 9:49am    
I've updated my answer. Rest is up to you. Good luck! :)
Maciej Los 4-Dec-14 14:28pm    
5ed!

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