I’m writing a small application in C# (.NET 4.0). I have a datagridview, each row represents one object. I want a combobox column that allows to choose a specific property of that object.
Example:
public class Car
{
public String Make {get; set;}
public BindingList<String> AllColors {get; set;}
public int SelectedColorIndex {get; set;}
}
Each row represents one Car object. Each (different) car object has it’s own selection of possible colors (AllColors). I want to have a column where you can set SelectedColorIndex by choosing one of the colors from AllColors (AllColors is specific to each Car object).
Note: I made up this example but it describes what I want to accomplish.
How can I accomplish this? The only solution that I found was to have a specific combobox outside of the datagridview using which you can change the selected row. And in row enter event I changed the datasource of the bindingsource to the current “AllColors”.
Thank you for your time and answers.
Here is the code behind of a working example where the colors available are filtered down to the colors provided in the bound object’s AllColors list.
The magic happens in the
CellBeginEditandCellEndEditevent handlers – there we provide each combo box cell with the list from the bound row and then reset it on exit.One thing this relies upon is having a master list which contains all colours – there is no way around this.
Also I’ve added handling for the case where a new row needs default values. All I do is set the selected index by default to one. Of course this wouldn’t work in the real world, you would need something a bit smarter! The
DefaultValuedNeededevent is describe here on MSDN.1 I first learned how to do this from the DataGridView FAQ, a great resource written by Mark Rideout, the program manager at the time for the
DataGridViewat Microsoft. The example in the FAQ filters based upon another combobox, and uses DataTables but the principle is the same.