DataGridViewComboBoxColumn设置DisplayMember和ValueMember

时间:2018-10-18 13:09:23

标签: c# winforms

我想填充DataGridViewComboBoxColumnCombobox应该代表此struct

internal struct IndexField
{
    public IndexField(int id, string name)
    {
        ID = id;
        Name = name;
    }

    public int ID { get; private set; }
    public string Name { get; private set; }
}

实施:

    public void Populate(IndexField[] indexFields)
    {
        DataGridViewComboBoxColumn indexFieldColumn = new DataGridViewComboBoxColumn()
        {
            HeaderText = "Index Fields"
        };

        indexFieldColumn.DataSource = indexFields;
        indexFieldColumn.DisplayMember = nameof(IndexField.Name);
        indexFieldColumn.ValueMember = nameof(IndexField.ID);

        dataGridView.Columns.Add(indexFieldColumn);

        for (int i = 0; i < 5; i++) // FOR TESTING PURPOSES ONLY => add some rows
        {
            dataGridView.Rows.Add(indexFields[0].Name); // use first combobox item as selected
        }
    }

运行代码时出现此错误

enter image description here

我想设置一个显示的值,但还要设置一个值成员。相当于HTML的

<select>
  <option value="ID1">Item1</option>
  <option value="ID2">Item2</option>
  <option value="ID3">Item3</option>
</select>

我该如何实现?

1 个答案:

答案 0 :(得分:0)

您可以仅通过datagrid的属性配置组合框。您不需要手动添加它们。只需右键单击DataGrid->编辑列。

Properties