Blorgbeard
Blorgbeard

Reputation: 103535

How do I set up a DataGridView ComboBoxColumn with a different DataSource in each cell?

I am setting up a DataGridViewComboBoxColumn like this:

var newColumn = new DataGridViewComboBoxColumn() {
    Name = "abc"
};
newColumn.DataSource = new string[] { "a", "b", "c" }; 
dgv.Columns.Add(newColumn);

This works: each row has a dropdown box in that column, populated with a, b, c.

However, now I would like to trim the list for certain rows. I'm trying to set the list per row like this:

foreach (DataGridViewRow row in dgv.Rows) {
    var cell = (DataGridViewComboBoxCell)(row.Cells["abc"]);        
    cell.DataSource = new string[] { "a", "c" };                        
}

However, this code has no effect - every row still shows "a", "b", "c".

I have tried replacing new string[] with new List<string> and new BindingList<string>, both to no avail.

I also have tried removing the code that sets newColumn.DataSource, but then the lists are empty.

How should I go about doing this properly?

Upvotes: 11

Views: 60162

Answers (2)

SwDevMan81
SwDevMan81

Reputation: 50028

The following works for me:

DataGridViewComboBoxColumn newColumn = new DataGridViewComboBoxColumn();
newColumn.Name = "abc";
newColumn.DataSource = new string[] { "a", "b", "c" };
dataGridView1.Columns.Add(newColumn);

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(row.Cells["abc"]);
    cell.DataSource = new string[] { "a", "c" };
}

You could also try (this also works for me):

for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
   DataGridViewComboBoxCell cell = 
       (DataGridViewComboBoxCell)(dataGridView1.Rows[row].Cells["abc"]);
   cell.DataSource = new string[] { "f", "g" };
}

Upvotes: 22

Andy_Vulhop
Andy_Vulhop

Reputation: 4789

Another option is to try databinding on the row level. Try using the event OnRowDataBound event. Then you can programatically set what is in the combo box based on the contents of that row.

Of course, this presumes you are databinding you grid.

Upvotes: 0

Related Questions