如何向DataGridViewComboBoxColumn中添加选项?
解决方法
情况1:所有行下拉选项一致(推荐)
如果所有行的下拉框都需要显示相同的name列表,直接给整个DataGridViewComboBoxColumn设置数据源更高效:
- 先收集所有子对象的
name到集合:
// yourMainObjectList 是绑定DataGridView的主对象列表 // ChildObjectList 是每个主对象里带name字段的子对象列表 List<string> nameList = yourMainObjectList .SelectMany(mainObj => mainObj.ChildObjectList.Select(child => child.name)) .Distinct() // 去重可选 .ToList();
- 找到目标列并设置数据源:
DataGridViewComboBoxColumn comboColumn = paymentTable.Columns[6] as DataGridViewComboBoxColumn; if (comboColumn != null) { comboColumn.DataSource = nameList; // 如果直接绑定子对象而非字符串,需设置显示字段 // comboColumn.DisplayMember = "name"; // comboColumn.ValueMember = "name"; // 若需要存储对应值可设置 }
情况2:每行下拉选项不同
如果每行需要展示不同的name列表,需将单元格强制转换为DataGridViewComboBoxCell后操作:
// 获取目标行的下拉单元格并转换类型 DataGridViewComboBoxCell comboCell = paymentTable.Rows[i].Cells[6] as DataGridViewComboBoxCell; if (comboCell != null) { // 清空原有项(按需选择) comboCell.Items.Clear(); // 遍历当前行对应主对象的子对象列表,添加name foreach (var childObj in yourMainObjectList[i].ChildObjectList) { comboCell.Items.Add(childObj.name); } // 可选:设置默认选中项 // comboCell.Value = yourMainObjectList[i].ChildObjectList.FirstOrDefault()?.name; }
原代码问题说明
直接获取的Cells[6]是DataGridViewCell基类,该类型没有Items属性,必须转换为具体的DataGridViewComboBoxCell类型,才能访问下拉框的项集合。
内容的提问来源于stack exchange,提问作者user28314043
相关产品推荐
相关产品推荐

