System.ArgumentException:DataGridViewComboBoxCell值无效

LEM*_*ANE 3 .net c# datagridview winforms datagridviewcomboboxcell

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);
Run Code Online (Sandbox Code Playgroud)

以编程方式将数据分配给的有效方法是什么DataGridViewComboBoxCell

小智 15

要解决此问题,只需为DataGridView添加"DataError".这就是全部步骤:双击datagridview并从事件列表中选择"dataerror"事件.

DataError事件使您可以处理在数据处理操作期间由控件调用的代码中抛出的异常.

而已 :)

  • 只是好奇 - 但是捕获错误并对其无所作为是不是不错的做法?我目前正在努力解决这个问题,我无法弄清楚是否可以阻止错误被抛出. (2认同)

Zol*_*ari 6

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

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

例如:

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
    e.Cancel = true;
}        
Run Code Online (Sandbox Code Playgroud)


rol*_*dow 5

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

// Combo
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.DataSource = Enum.GetValues(typeof(PhoneNumberType));
combo.DataPropertyName = "PhoneNumberType";
combo.Name = "PhoneNumberType";
phoneNumberGrid.Columns.Add(combo);
Run Code Online (Sandbox Code Playgroud)

现在,当 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;
}
Run Code Online (Sandbox Code Playgroud)

..异常消失了。