[英]Enable value not in the list to be shown - System.ArgumentException: DataGridViewComboBoxCell value is not valid
[英]System.ArgumentException: DataGridViewComboBoxCell value is not valid
dataGridView.Rows.Add(
metaData.Offset.ToString("X2"),
metaData.Length,
metaData.Format, // This parameter goes to a ComboBox cell which throws an
metaData.Description, // exception above
null,
null);
以编程方式将数据分配给DataGridViewComboBoxCell
的有效方法是什么?
要解决这个问题,只需为 DataGridView 添加“DataError”即可。 就是这样,步骤:双击datagridview并从事件列表中选择“dataerror”事件。
DataError 事件使您能够处理在数据处理操作期间由控件调用的代码中引发的异常。
就是这样 :)
要解决此问题,请为 DataGridView 添加“DataError”事件,然后
只需这样写: e.Cancel = true;
例如:
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
e.Cancel = true;
}
聚会有点晚,但我认为这对其他人仍然有用。 就我而言,我收到此错误是因为我添加了一个基于枚举的组合框,如下所示:
// Combo
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = Enum.GetValues(typeof(PhoneNumberType));
combo.DataPropertyName = "PhoneNumberType";
combo.Name = "PhoneNumberType";
phoneNumberGrid.Columns.Add(combo);
现在,当 DataGridView 创建一个新的(空)行时,这个空值无法映射到组合框。 因此,我没有忽略错误,而是为组合框设置了默认值。 我添加了事件DefaultValuesNeeded
并且只是将值设置为枚举中的项目之一。 像这样:
private void phoneNumberGrid_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
// Prevent System.ArgumentException: DataGridViewComboBoxCell value is not valid
e.Row.Cells["PhoneNumberType"].Value = PhoneNumberType.Private;
}
.. 异常消失了。
我有一个类似的问题,我用Dictionary<int,string> myDict
填充了我的 DataSource ,我想在其中显示字符串但有一个整数作为要使用的基础值:
comboboxcolumn.DataSource = new BindingSource(myDict, null);
comboboxcolumn.ValueMember = "Key";
comboboxcolumn.DisplayMember = "Value";
导致我遇到麻烦的是我正确设置: comboboxcolumn.ValueType = typeof(int);
但是在CellValueNeeded()
方法中,我然后设置e.Value = someValueOfMyDict;
这是一个string
。 改用int
键,您可以消除错误,而不是捕获它并对其进行处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.