0
votes

I have the following class:

Imports Cognex.InSight
Imports Newtonsoft.Json

Public Class VariableViewModel

    Public Enum VariableTypes
        EditRegion
        Enumerated
        Input
        Momentary
        Toggle
    End Enum

    Public Property CellLocation As CvsCellLocation

    Public Property Name As String

    Public Property Values As Dictionary(Of String, String)

    Public Property VariableType As VariableTypes

    Public Function ToJson() As String
        Return JsonConvert.SerializeObject(New With {Key Name, CellLocation, Values, VariableType})
    End Function

End Class

This class is being serialized and then eventually deserialized back and stored into a List. This list is ultimately bound to a DataGridView using a BindingSource as such:

' Private ReadOnly _variables As List(Of VariableViewModel)
Dim source As BindingSource = New BindingSource() With {
    .DataSource = _variables
}
DataGridViewVariables.DataSource = source

The issue that I'm running into is that the Column names in the DataGridView are not a one-to-one match to the properties on the class. Plus I wanted to add two button columns at the end of the DataGridView.

Without clearing the Columns, then binding the DataGridView, and then manually setting up the Button columns, is there a way to match the column names to the class property names?

1
While you should use the answer I have provided below, it's worth noting that you can independently control the order columns are displayed in the grid using their DisplayIndex. If you did want to display all data source properties with default names with subsequent button columns, you could add just the button columns at design time, set the DataSource to automatically create the rest of the columns at run time and then set the DisplayIndex properties to display the button columns last. - jmcilhinney

1 Answers

2
votes

The DataPropertyName property of a DataGridViewColumn determines what column/property of the data source it binds to. You can add columns to the grid yourself, either in the designer or in code, and set that property for each column. Before you set the DataSource, you set AutoGenerateColumns to False and then only the existing columns will be bound as specified and no new columns will be created.