Hi @Hobbyist_programmer ,
You can use reflection to dynamically determine the properties of the derived classes and add them as columns in the DataGridView.
Private Sub GetProperties()
' Clear existing columns
DataGridView1.Columns.Clear()
' Keep track of added columns to avoid duplicates
Dim addedColumns As New HashSet(Of String)
' Add columns for properties of the base class
For Each prop As PropertyInfo In GetType(Equipment).GetProperties()
If Not addedColumns.Contains(prop.Name) Then
DataGridView1.Columns.Add(prop.Name, prop.Name)
DataGridView1.Columns(prop.Name).DataPropertyName = prop.Name
addedColumns.Add(prop.Name)
End If
Next
' Iterate through the items in the list to determine additional columns based on the derived class type
For Each item As Equipment In equipments
Dim itemType = item.GetType()
Dim properties = itemType.GetProperties()
For Each prop As PropertyInfo In properties
' Exclude properties from the base class
If prop.DeclaringType IsNot GetType(Equipment) Then
If Not addedColumns.Contains(prop.Name) Then
DataGridView1.Columns.Add(prop.Name, prop.Name)
DataGridView1.Columns(prop.Name).DataPropertyName = prop.Name
addedColumns.Add(prop.Name)
End If
' Populate cell with corresponding data
Dim rowIndex As Integer = equipments.IndexOf(item)
Dim columnIndex As Integer = DataGridView1.Columns(prop.Name).Index
Dim value As Object = prop.GetValue(item)
DataGridView1.Rows(rowIndex).Cells(columnIndex).Value = value
End If
Next
Next
End Sub
Best Regards.
Jiachen Li
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.