views:

6284

answers:

2

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?

+4  A: 

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.Columns.Count; row++)
        {
            DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(dataGridView1.Rows[row].Cells["abc"]);
            cell.DataSource = new string[] { "f", "g" };
        }
SwDevMan81
Hmm, that works for me too - in a clean test project. It must be something I'm doing differently..
Blorgbeard
Ok, the problem was something to do with the fact that my DataGridView had AutoSizeColumnMode set to AllCells. I think it was validating the cells' values before their datasource was set (or something).
Blorgbeard
Helped me with my problem!
XXXXX
A: 

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.

Andy_Vulhop
I am databinding, but this is winforms, not web. winforms datagridview does not appear to have this event..
Blorgbeard