Hello @Hobbyist_programmer
For your requirements, implement INotifyPropertyChanged Interface for allowing immediate updates to the user interface. If we were to simply set the list (in this case of Person) to the DataGridView it would seem we are done although there is no sorting so a custom BindingList (found here) is needed and on top of this a BindingSource to tie things together.
You can copy code below or copy the full code including the custom BindingList from the following GitHub repository.
Here is the Person class which implements INotifyPropertyChanged.
Imports System.ComponentModel
Imports System.Runtime.CompilerServices
Public Class Person
Implements INotifyPropertyChanged
Public Property Id() As Integer
Public Property FirstName() As String
Public Property LastName() As String
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Protected Overridable Sub OnPropertyChanged(<CallerMemberName> Optional ByVal propertyName As String = Nothing)
PropertyChangedEvent?.Invoke(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
And a class for some mocked up data.
Public Class Mocked
Public Shared ReadOnly Property PeopleList() As List(Of Person)
Get
Return New List(Of Person) From {
New Person() With {.Id = 1, .FirstName = "Karen", .LastName = "Payne"},
New Person() With {.Id = 2, .FirstName = "Bill", .LastName = "Smith"},
New Person() With {.Id = 3, .FirstName = "Mary", .LastName = "Jones"},
New Person() With {.Id = 4, .FirstName = "Kim", .LastName = "Adams"}}
End Get
End Property
End Class
Form code for displaying, minimal editing and a mocked up add new Person.
Public Class Form1
Private peopleBindingList As SortableBindingList(Of Person)
Private peopleBindingSource As New BindingSource()
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
peopleBindingList = New SortableBindingList(Of Person)(Mocked.PeopleList)
peopleBindingSource.DataSource = peopleBindingList
dataGridView1.DataSource = peopleBindingSource
dataGridView1.Columns("id").Visible = False
End Sub
Private Sub CurrentPersonButton_Click(sender As Object, e As EventArgs) _
Handles CurrentPersonButton.Click
If peopleBindingSource.Current Is Nothing Then
Return
End If
Dim currentPerson = peopleBindingList(peopleBindingSource.Position)
MessageBox.Show($"{currentPerson.Id}, {currentPerson.FirstName}, {currentPerson.LastName}")
End Sub
Private Sub NewPersonButton_Click(sender As Object, e As EventArgs) Handles NewPersonButton.Click
peopleBindingList.Add(New Person() With
{
.Id = peopleBindingList.Select(Function(p) p.Id).Max() + 1,
.FirstName = "Jude",
.LastName = "Lennon"
})
End Sub
End Class
Screen shot