Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 481
Blorgbeard Avatar asked Jul 07 '09 00:07

Blorgbeard


1 Answers

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" };
}
like image 167
SwDevMan81 Avatar answered Oct 24 '22 03:10

SwDevMan81