Search code examples
c#datagridviewcombobox

c# Populating a combobox from datagridview with conditions


In my project I'm using a database like this

ID | Name   | Function
1  | John   | CH
2  | Maria  | CD
3  | Nikita | CH
4  | Carin  | CH

I'm using this piece of code to populate the combobox with all the names:

DataTable dt = new DataTable("Person");
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Function", typeof(string));

for (int i = 0; i < dataGridView.Rows.Count; i++)
    dt.Rows.Add(MyComboBox.Items.Add(dataGridView[2, i].Value.ToString()

Now I'd like to populate the combobox with only some names, with a formula like this:

for each name with CH Function - > add that name in MyCombobox

I'm stuck with that, could you help me?


Solution

  • Try this

    MyComboBox.Items.Clear();
    foreach (DataGridViewRow row in dataGridView.Rows)
    {
        if (row.Cells["Function"].Value!=null && row.Cells["Function"].Value.Equals("CH"))
        MyComboBox.Items.Add(row.Cells["Name"].Value.ToString());
    }