Bind or show object properties values in datagridview rows?

Hobbyist_programmer 621 Reputation points
2020-12-04T22:55:45.677+00:00

Hallo I am looking for a way to bind object properties to data grid view row items . for example i have sample class like blow

Public Class Sample

Public Readonly Property Prop1 as integer
Public Readonly Property Prop2 as integer

End Class 

and a datagridview with 3 columns which shows the description and value of the Prop1 and Prop2 and may be i can hide the property column

Property Description Value
Prop1 Description 1 xx
Prop2 Description 2 xx

Is there a way to do this so that the properties values are always synced/changes immediately? Thanks.

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,580 questions
0 comments No comments
{count} votes

Accepted answer
  1. Peter Fleischer (former MVP) 19,231 Reputation points
    2020-12-05T19:43:25.8+00:00

    Hi,
    you can use Reflection to get names and values of properties for displaying in Datagrid like in following demo:

    Imports System.Reflection
    
    Public Class Form10
    
      Private dgv As New DataGridView With {.Dock = DockStyle.Fill, .AutoGenerateColumns = True}
    
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Controls.Add(dgv)
        '
        Dim s As New Sample
        '
        dgv.DataSource = New PropertyList(s)
      End Sub
    
      Private Class PropertyList
        Inherits List(Of PropertyItem)
        Public Sub New(obj As Object)
          For Each prop In obj.GetType().GetProperties(BindingFlags.Public Or BindingFlags.Instance)
            Me.Add(New PropertyItem(obj, prop))
          Next
        End Sub
      End Class
    
      Public Class PropertyItem
        Public Sub New(obj As Object, prop As PropertyInfo)
          Me._obj = obj
          Me._prop = prop
        End Sub
        Private _obj As Object
        Private _prop As PropertyInfo
        Public ReadOnly Property PropertyName As String
          Get
            Return Me._prop.Name
          End Get
        End Property
        Public ReadOnly Property PropertyValue As Object
          Get
            Return Me._prop.GetValue(Me._obj)
          End Get
        End Property
      End Class
    
      Public Class Sample
        Public ReadOnly Property Prop1 As Integer = 1
        Public ReadOnly Property Prop2 As Integer = 2
      End Class
    
    End Class
    
    0 comments No comments

5 additional answers

Sort by: Most helpful
  1. Hobbyist_programmer 621 Reputation points
    2020-12-06T11:05:48.977+00:00

    Thanks Karen and Peter for the answer . I wanted to mark both as answer but i could not mark it in this forum.