DataGridViewComboBoxCell Binding - “value is not v

2019-01-09 05:38发布

I'm trying to bind separate ComboBox cells within a DataGridView to a custom class, and keep getting an error

DataGridViewComboBoxCell value is not valid

I'm currently assigning the data source for the cell to an IList<ICustomInterface> from a Dictionary I've got. Upon setting the data source however, the index for the ComboBoxCell isn't set, so it has an invalid value selected.

I'm trying to figure out how to get it to select a real value, e.g. the 0th item within the list it has been given to remove this error, or find another way to solve the problem. Anyone have any suggestions?

9条回答
够拽才男人
2楼-- · 2019-01-09 06:13

I managed to find the solution not long after posting the question. For anyone else:

The problem was that I was trying to assign the DataGridViewComboBoxCell.Value to an object, expecting that because the Cell was bound to a data source that it would automatically find the object in the source and update.

This wasn't actually the case, you actually need to set the value equal to that of the ValueMember property for it to correctly update the value and binding. I believe I was using a property 'Name' for both ValueMember and DisplayMember (controls how the renders in the cell) so setting the Value to interface.ToString() (rather than the interface instance) works for the majority of cases. Then I catch and ignore any DataError exceptions that occur while I'm changing the source around.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-09 06:13

I am having the same problem. After populating my ComboBox column in the (unbouod) DataGrid, I solved my problem by setting the ValueMember property of the DataGridViewComboBoxColumn Apparently, just relying on the ToString() property of the objects in the ComboBox is not enough.

Actual code:

/// <summary>
/// Populate the dataGridSplitVolumes data grid with all existing qualifications for the plan.
/// </summary>
/// <param name="bonus"></param>
private void PopulateDataGridSplitVolumes(Bonus_Group bonus)
{
  try
  {
    List<Qualification> qualifications = Qualification.Load(this.groupBonus.PlanID, this.ConnectionString);
    foreach (Qualification qual in qualifications)
    {
      DataGridViewComboBoxColumn col = (DataGridViewComboBoxColumn)this.dataGridSplitVolumes.Columns[0];
      col.Items.Add(qual);                    
    }
    SplitVolumeGrid_QualificationColumn.ValueMember = "Name";
  }
  catch (Exception ex)
  {
#if DEBUG
    System.Diagnostics.Debugger.Break();
#endif
    throw ex;
  }
}//PopulateDataGridSplitVolumes     
查看更多
smile是对你的礼貌
4楼-- · 2019-01-09 06:15

Here's my simple solution when using enums

ColumnType.ValueType = typeof (MyEnum);
ColumnType.DataSource = Enum.GetValues(typeof (MyEnum));

you can do that just after "InitializeComponent();"

查看更多
登录 后发表回答