c# - How do I bind a DataGridViewComboBoxColumn to the list property of the parent row's bound object? -
given following classes:
public class shirt { public string description { get; set; } public list<color> coloroptions { get; set; } public int selectedcolorid { get; set; } } public class color { public int id { get; set; } public string label { get; set; } }
why can't combobox show in datagridview using following code?
list<shirt> foundshirts = _dbshirtrepo.getshirts(); var namecolumn = new datagridviewtextboxcolumn(); namecolumn.datapropertyname = "description"; namecolumn.headertext = "description"; var colorselectcolumn = new datagridviewcomboboxcolumn(); colorselectcolumn.datapropertyname = "coloroptions"; colorselectcolumn.displaymember = "label"; colorselectcolumn.valuemember = "id"; datagridview1.columns.add(namecolumn); datagridview1.columns.add(colorselectcolumn); datagridview1.datasource = foundshirts;
try this:
private void datagridview1_cellclick(object sender, datagridviewcelleventargs e) { if (e.columnindex == 1) { datagridviewcomboboxcell combo = this.datagridview1[1, e.rowindex] datagridviewcomboboxcell; combo.datasource = ((shirt)datagridview1.rows[e.rowindex].databounditem).coloroptions; } }
as can see, have provide datasource
per request because can have 1 @ time. there's no way pre-set different data sources each combo in each row.
you can improve above solution concept same:
- user clicks, hovers or otherwise "activates" cell
- set
datasource
of column's combo before user has chance open it
this way user not aware of shenanigans going on , can offer different choice every individual row.
note: i'm not 100% sure of how datagridviewcomboboxcell
operates, it's entirely possible caches , persists data sources experiment bit before relying on it.
Comments
Post a Comment