I'm having to modify an old Winforms app to add a combo box to a DataGridView.
The data source for the grid is a normal list object with primitives which binds fine but now the object in the list has its own list of objects. eg:
public class Person
{
public string Name {get; set;}
public int Age {get; set;}
public List<Colors> ColorList {get; set;}
}
and the Colors lets say is something like:
public class Colors
{
public string Name;
}
The list in Person is simply a list. It's not a foreign key with one colour linked to each person. The grid has to show each person and a final column with all the colors in that list in a combobox for the user to select one.
So the Grid has 3 columns. 2 DataGridViewTextBoxColumn and 1 DataGridViewComboBoxColumn
Setting the data properties in the designer and a datasource to the List of Person's shows the Name and Age values but the Combobox is empty and has no drop down.
Manually adding the columns, the rows and assigning the cell item values doesn't work either.
It seems unless I set the Columns DataPropertyName, I get an empty combobox.
As the grid is bound to the List I can only set the DataPropertyName to a property on the Person object and then the DisplayMember and ValueMember to members of the Color object but this doesn't work either..it seems to be a sort of Foreign key setup which would select 1 color matching some id from the Person object but this isn't what I need.
I just want every item from the ColorList list that has been added to the Person object to appear in the dropdown of the associated Person
What am I missing as this seems such a simple thing.
Edit: Here is some code I've tried to manually put data into the grid.
grd2.AutoGenerateColumns = false;
var colors = new List<Colors>
{
new Colors() { Color = "red", Id = 1 },
new Colors() { Color = "blue", Id = 1 }
};
var persons = new List<Person>
{
new Person() { Name = "Bob", Age = 20, ColourList = colors },
new Person() { Name = "Jane", Age = 24, ColourList = colors }
};
foreach (var person in persons)
{
var row = new DataGridViewRow();
var cell1 = new DataGridViewTextBoxCell { Value = person.Name };
var cell2 = new DataGridViewTextBoxCell { Value = person.Age };
var cell3 = new DataGridViewComboBoxCell { ValueType = typeof(string) };
person.ColourList.ForEach(x => cell3.Items.Add(x.Color));
row.Cells.AddRange(new DataGridViewCell[] {cell1, cell2});
row.Cells.Add(cell3);
grid.Rows.Add(row);
}
This populates the Name and Age columns but the dropdown list doesn't even dropdown. The grid has a 3 columns defined in the designer. 2 text and 1 combo. Obviously in this example the colors are fixed for both Bob and Jane but this wouldn't be the case in reality..this is just an example.