Sidav
Sidav

Reputation: 53

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?

Upvotes: 0

Views: 3723

Answers (2)

Alexander Petrov
Alexander Petrov

Reputation: 14231

Let's do it right!

The DataTable is designed for data storage.
DataGridView and ComboBox are designed for data represent.

Puts data in DataTable

DataTable dt = new DataTable("Person");

dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Function", typeof(string));

dt.Rows.Add("1", "John", "CH");
dt.Rows.Add("2", "Maria", "CD");
dt.Rows.Add("3", "Nikita", "CH");
dt.Rows.Add("4", "Carin", "CH");

Bind raw data to DataGridView

dataGridView.DataSource = dt;

Now we need to bind filtered data to the ComboBox

DataView view = dt.AsDataView();
view.RowFilter = "Function = 'CH'";
comboBox.DisplayMember = "Name";
comboBox.DataSource = view;

Ready!

Now, if you change data in the DataGridView, those changes will automatically display in the ComboBox.

For example, change the Function column value from CH to CD for John, and he disappears from the ComboBox.

Also, you can dynamically change the filter conditions.

Specify

view.RowFilter = "Function = 'CD'";

Voila! The ComboBox now shows other names.

Upvotes: 2

Nitesh Shaw
Nitesh Shaw

Reputation: 216

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());
}

Upvotes: 1

Related Questions