Search code examples
.netdatagridviewdatagridviewcomboboxdatagridviewcomboboxcell

Can items of DataGridViewComboBoxColumn be of custom object type?


In a DataGridViewComboBoxColumn I need to use values of my class MyValue as combo box items (in Items property), but I am getting a DataError during the runtime when leaving the combobox column in which I selected any of my values.

How can be DataGridViewComboBoxColumn used with values of custom type (without DataError errors)?


More details:

Class MyValue looks like this:

Public Class MyValue
    Implements ICloneable
    Public Property Definition As String
    Public Shadows Function ToString() As String
        Return "DEF" & Definition
    End Function
    Public Function Clone() As Object Implements ICloneable.Clone
        Return MemberwiseClone()
    End Function
End Class

The DataSource property is not set and is expected not to be mandatory.


Solution

  • Problems with DataError are present until given DataGridViewComboBoxColumn has properties DisplayMember and ValueMember empty.

    • Set DisplayMember to name of property which can serve as displayed value.
    • Set ValueMember to name of property which can serve to identify the value object.

    Note that with unbound column they cannot be set in designer, because it reverts them back to "", so they have to be set programmatically.

    Example:

    DisplayMember = "Definition"
    ValueMember = "ThisObject"
    

    ...with self-referencing property ThisObject added into the MyValue class:

    Public Class MyValue
        '...
        Public Property ThisObject As MyValue
        Public Sub New()
            MyBase.New()
            ThisObject = Me
        End Sub
        '...
    End Class