DataGridViewComboBoxColumn设置DisplayMember和ValueMember [英] DataGridViewComboBoxColumn setup DisplayMember and ValueMember

查看:118
本文介绍了DataGridViewComboBoxColumn设置DisplayMember和ValueMember的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想填充DataGridViewComboBoxColumn。 Combobox应代表此结构



I want to populate a DataGridViewComboBoxColumn. The Combobox should represent this 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; }
    }

实施:

Implementation:

        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
            }
        }

运行代码时我得到这个错误







我想设置一个显示值,但也要设置一个值成员。一个HTML等价物将是b


When running the code I get this error



I want to setup a displayed value but also setup a value member. A HTML equivalent would be

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

如何实现这一目标?

¥ b $ b  [1]:https://i.stack.imgur.com/N0suc.jpg

How can I achieve this?

  [1]: https://i.stack.imgur.com/N0suc.jpg

推荐答案

这个的一个常见原因是对于DataGridView的DataSource的列设置,显示成员的值不存在。

A common reason for this is that the value for display member does not exists for the column setup for the DataSource of the DataGridView.

您是否尝试过订阅DataGridView的DataError事件?

Have you tried subscribing to DataError event of the DataGridView?

您是否验证了Item1,Item2,Item3作为DataGridViewComboBox列的有效值存在?

Have you verified the values Item1, Item2, Item3 exists as valid values for the DataGridViewComboBox column?

以下显示了一个有效的
代码示例

The following shows a working code sample for what you are after.


这篇关于DataGridViewComboBoxColumn设置DisplayMember和ValueMember的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆