4
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

4

4 回答 4

16

要解决此问题,只需为 DataGridView 添加“DataError”即可。就是这样,步骤:双击datagridview并从事件列表中选择“dataerror”事件。

DataError 事件使您能够处理在数据处理操作期间由控件调用的代码中引发的异常。

而已 :)

于 2012-02-04T18:01:46.067 回答
6

为解决此问题,为 DataGridView 添加“DataError”事件,然后

只需这样写:e.Cancel = true;

例如:

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
    e.Cancel = true;
}        
于 2017-08-30T05:23:57.830 回答
3

聚会有点晚了,但我认为这对其他人仍然有用。就我而言,我收到了这个错误,因为我添加了一个基于这样的枚举的组合框:

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

..异常消失了。

于 2019-03-06T07:48:44.053 回答
0

我有一个类似的问题,我用 a 填充了我的 DataSource Dictionary<int,string> myDict,我想在其中显示字符串,但有一个整数作为要使用的基础值:

comboboxcolumn.DataSource = new BindingSource(myDict, null);
comboboxcolumn.ValueMember = "Key";
comboboxcolumn.DisplayMember = "Value";

造成我麻烦的是我正确设置:comboboxcolumn.ValueType = typeof(int); 但在CellValueNeeded()方法中,我设置e.Value = someValueOfMyDict;了 which is a string. 改为使用int密钥,您可以消除错误,而不是捕获它并让它不处理。

于 2020-12-24T09:12:54.630 回答