|
|
Title | Make a DataGridView control use an array of objects for a data source in Visual Basic .NET |
Description | This example shows how to make a DataGridView control use an array of objects for a data source in Visual Basic .NET. |
Keywords | DataGridView, data source, array, objects, Visual Basic .NET, VB.NET |
Categories | Controls, VB.NET |
|
|
Simply build an array of objects and assign it to the DataGridView's DataSource property. The control automatically displays the values of each object's public properties.
The following code shows how the program assigns the control to display an array of Person objects. The code also sets column headers for the control. (By default the control uses the properties' names.)
|
|
' Make the data array.
Dim people(3) As Person
people(0) = New Person("Ann", "Able")
people(1) = New Person("Ben", "Baker")
people(2) = New Person("Cindy", "Carruthers")
' Make the control use the array as its data source.
dgvPeople.DataSource = people
' Make column headings.
dgvPeople.Columns(0).HeaderText = "Given Name"
dgvPeople.Columns(1).HeaderText = "Surname"
|
|
Note that a value must be a property not a public field to be visible. The following code shows how the program defines the Person class's FirstName property.
|
|
Private m_FirstName As String
Public Property FirstName() As String
Get
Return m_FirstName
End Get
Set(ByVal value As String)
m_FirstName = value
End Set
End Property
|
|
|
|
|
|