BindingList to DataGridView, but get empty cells

I’m trying to place BindingList data into a default DataGridView, but without success. If I run the Form, it shows a DataGridView with empty rows. So the number of rows is correct, but the data itself is missing.

Imports System.ComponentModel

Public Class Form1

Public Sub New()
    InitializeComponent()

    'Declare BindingList
    Dim bList As BindingList(Of User)

    'Init BindingList Constructor
    bList = New BindingList(Of User)()

    'List -> BindingList
    'Dim bindingList = New BindingList(Of Person)(list)

    'BindingList Settings
    bList.AllowNew = True
    bList.AllowRemove = True
    bList.AllowEdit = True
    bList.RaiseListChangedEvents = True

    'Add Object
    bList.Add(New User() With {.id = 1, .firstName = "Jeff", .lastName = "Tree"})
    bList.Add(New User() With {.id = 2, .firstName = "Loes", .lastName = "Stone"})

    'BindingList -> DataGridView
    Dim source = New BindingSource(bList, Nothing)
    DataGridView1.DataSource = bList
    End Sub
End Class

Public Class User
    Sub New()
    End Sub

Public id As Integer
Public firstName As String
Public lastName As String

End Class

Result:

DataViewGrid without the values

>Solution :

The User class only contains public fields (which cannot be used for data binding). You should use properties instead:

Public Class User
    Public Property Id As Integer
    Public Property FirstName As String
    Public Property LastName As String
End Class

Then, you can either remove the columns that you manually added to the DataGridView (in which case, they will be automatically generated for you) or you can set the AutoGenerateColumns property of the DGV to false, but in that case, you will also need to set the DataPropertyName property of each column to match the property name in your class.

Leave a Reply