DataGridViewComboBoxCell手动设置值,值无效
这是我的代码:
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.DataSource
设置为Person of List,并设置DataGridViewComboBoxColumn.ValueType = typeof(Person)
,而不是添加到DataGridViewComboBoxColumn.Items
。
应该这样做。 虽然你问这个已经两个月了,但你的问题可能已经失去了它的紧迫感。
我也有这个问题。 我以一种肮脏的方式暂时解决了这个问题。
DataGridViewComboBoxCell的Value属性必须是Items属性(或绑定的DataSource)中包含的值之一
问题是,因为我不知道是什么原因,当执行进入该Cell的DataGridView.CellFormatting
事件处理程序时,单元格的Items列表(或当我尝试不手动输入Items时的DataSource)被清除。
我的脏修复是处理DataGridView.DataError
事件并在那时填充(再次)DataGridViewComboBoxCell.Items。
Private Sub myDataGridView_DataError(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs) _ Handles dgvServicesToTransfer.DataError 'Dirty Fix If e.ColumnIndex = myComboBoxColumn.Index Then Dim row As DataGridViewRow = dgvServicesToTransfer.Rows(e.RowIndex) ' Fill in your DataGridViewComboBoxCell's Items here: ' ... ' ... If allWentWell Then ' Cancel the exception e.ThrowException = False End If End If End Sub End Class
PS:对不起VB.Net的答案,如果你有“翻译”的问题,请问。
我有类似的问题。 听起来很奇怪,我通过存储只向DataGridViewComboBoxCell.Items添加字符串来解决它。 添加对象(使用ToString()很好地实现了等)导致了这些“数据错误”问题,但添加字符串工作正常。
尝试使用enum作为您的人名
enum person { John, Andy, Sepehr };
使用此枚举为您的combobox添加名称
myDataGridViewComboBoxCell.Items.Add ( person.andy.tostring(),number );
现在当你想要再次设置vale时使用枚举。 tyhis将解决你的问题。
myDataGridViewComboBoxCell.Value = person.Andy.ToString() ;
记得使用 – > ToString()
! 为我工作! 🙂