c# - DataGridViewComboBoxCell 手动设置值,值无效

标签 c# datagridview

这是我的代码:

        private class Person
        {
            private string myName;
            private int myValue;

            public Person(string name, int value)
            {
                myName = name; 
                myValue = value;
            }
            public override string ToString()
            {
                return myName;
            }

            public string Name
            {
                get { return myName; }
                set { myName = value; }
            }

            public int Value
            {
                get { return myValue; }
                set { myValue = value; }
            }
        }

我用它来填充 DataGridViewComboBoxCell,如下所示:

myDataGridViewComboBoxCell.ValueMember = "Value";
myDataGridViewComboBoxCell.DisplayMember = "Name";
myDataGridViewComboBoxCell.Items.Add(new Person("blabla", someNumber));

我现在要做的就是选择一个人:

myDataGridViewComboBoxCell.Value = someNumber;

但不断出现“值无效”错误。知道为什么吗? 当我在程序中选择一个项目时,我可以看到正确的值 (someNumber),因此 Display 和 ValueMember 设置正确...

最佳答案

无需添加到 DataGridViewComboBoxColumn.Items,您需要将 DataGridViewComboBoxColumn.DataSource 设置为人员列表,并设置 DataGridViewComboBoxColumn.ValueType = typeof (人)

应该这样做。虽然考虑到您提出这个问题已经两个月了,但您的问题可能已经失去了紧迫感。

关于c# - DataGridViewComboBoxCell 手动设置值,值无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2753687/

相关文章:

Xbox 上的 C# UWP Windows.Web.Http.HttpClient 错误 401

c# - SQLite C# 和 DataGridView

c# - ComboBoxCell 中的自定义绘制项

C# 使用 IComparer 对 x 列进行排序

c# - 如何使用 C# 在 datagridview 中读取/加载文本 (*.txt) 文件值 ..?

c# - 使用 Thread.Sleep() 实现心跳

c# - 使用 C# 在 AutoCAD 2015 中环绕相机

c# - 如何建模独占行为并使其可配置

c# - 如何在 Winform DataGridView 中创建不同的单元格格式

c# - 如何读取 ASP.NET 中的 CSS 属性?