DataGridViewComboBoxCell绑定 - "值无效"

Ian*_*Ian 28 c# datagridview datagridviewcombobox

我正在尝试将DataGridView中的单独ComboBox单元绑定到自定义类,并继续收到错误

DataGridViewComboBoxCell值无效

我现在正在将单元格的数据源分配给IList<ICustomInterface>我所拥有的词典.但是,在设置数据源时,ComboBoxCell未设置索引,因此选择了无效值.

我试图弄清楚如何让它选择一个真正的值,例如列表中的第0个项目,它已被删除此错误,或找到解决问题的另一种方法.有人有什么建议吗?

Ian*_*Ian 33

在发布问题后不久,我设法找到了解决方案.对于其他任何人:

问题是我试图将DataGridViewComboBoxCell.Value一个对象分配给一个对象,期望因为Cell被绑定到一个数据源,它会自动在源中找到对象并进行更新.

实际上并非如此,您实际上需要将值设置为等于ValueMember属性的值才能正确更新值和绑定.我相信我正在为两者使用属性'Name' ValueMemberDisplayMember(控制在单元格中呈现的方式),因此将Value设置为interface.ToString()(而不是接口实例)适用于大多数情况.然后我捕获并忽略在我更改源时发生的任何DataError异常.

  • 对于遇到这种情况的任何其他人来说,你的意思是ValueMember属性需要等于单元格值 - DisplayMember是你想要看到的相应字段 (5认同)

Sau*_*eil 16

这是使用枚举时的简单解决方案

ColumnType.ValueType = typeof (MyEnum);
ColumnType.DataSource = Enum.GetValues(typeof (MyEnum));
Run Code Online (Sandbox Code Playgroud)

你可以在"InitializeComponent();"之后做到这一点.


小智 5

经过几个小时的尝试,我终于找到了一个可行的解决方案。

// Create a DataGridView
System.Windows.Forms.DataGridView dgvCombo = new System.Windows.Forms.DataGridView();

// Create a DataGridViewComboBoxColumn
System.Windows.Forms.DataGridViewComboBoxColumn colCombo = new 

System.Windows.Forms.DataGridViewComboBoxColumn();

// Add the DataGridViewComboBoxColumn to the DataGridView
dgvCombo.Columns.Add(colCombo);

// Define a data source somewhere, for instance:
public enum DataEnum
{
    One,
    Two,
    Three
}

// Bind the DataGridViewComboBoxColumn to the data source, for instance:
colCombo.DataSource = Enum.GetNames(typeof(DataEnum));

// Create a DataGridViewRow:
DataGridViewRow row = new DataGridViewRow();

// Create a DataGridViewComboBoxCell:
DataGridViewComboBoxCell cellCombo = new DataGridViewComboBoxCell();

// Bind the DataGridViewComboBoxCell to the same data source as the DataGridViewComboBoxColumn:
cellCombo.DataSource = Enum.GetNames(typeof(DataEnum));

// Set the Value of the DataGridViewComboBoxCell to one of the values in the data source, for instance:
cellCombo.Value = "Two";
// (No need to set values for DisplayMember or ValueMember.)

// Add the DataGridViewComboBoxCell to the DataGridViewRow:
row.Cells.Add(cellCombo);

// Add the DataGridViewRow to the DataGridView:
dgvCombo.Rows.Add(row);

// To avoid all the annoying error messages, handle the DataError event of the DataGridView:
dgvCombo.DataError += new DataGridViewDataErrorEventHandler(dgvCombo_DataError);

void dgvCombo_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
    // (No need to write anything in here)
}
Run Code Online (Sandbox Code Playgroud)

就这些。

  • @NaSo 记住!你需要解决问题,而不是忽视它。顺便说一句,您绑定了一个“cellCombo.DataSource”,这是完全错误的。事实上,当您设置“DataGridViewComboBoxColumn.DataSource”时,“DataGridViewComboBoxCell.DataSource”将自动绑定 (2认同)