DataGridViewComboBoxCell手动设置值,值无效

Jay*_*Jay 3 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; }
            }
        }
Run Code Online (Sandbox Code Playgroud)

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

myDataGridViewComboBoxCell.ValueMember = "Value";
myDataGridViewComboBoxCell.DisplayMember = "Name";
myDataGridViewComboBoxCell.Items.Add(new Person("blabla", someNumber));
Run Code Online (Sandbox Code Playgroud)

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

myDataGridViewComboBoxCell.Value = someNumber;
Run Code Online (Sandbox Code Playgroud)

但继续得到"价值无效" - 恐怖.任何想法为什么?当我在程序中选择一个项目时,我可以看到正确的值(someNumber),因此Display和ValueMember设置正确...

Spi*_*ike 10

而不是添加DataGridViewComboBoxColumn.Items,您需要设置DataGridViewComboBoxColumn.DataSource为人员列表,并设置DataGridViewComboBoxColumn.ValueType = typeof(Person).

应该这样做.虽然你问这个已经两个月了,但你的问题可能已经失去了它的紧迫感.