VB.NET DataGridView - Fill from ArrayList

April 10, 2018 Oclemy VB.NET DataGridView, VB.NET ArrayList 3 minutes, 17 seconds

In this class we see how to populate a DataGridView from an ArrayList.

DataGridView is a windows forms component that displays data in a customizable grid.

DataGridView ArrayList

To learn more about datagridview check our tutorial here.

We will have three columns in our DataGridView. Two of those columns we populate from arraylists while the last we generate random distances to populate.

Program.vb

Here's the full code. Not we are not using designer.


Imports System
Imports System.Collections
Imports System.Drawing
Imports System.Windows.Forms

Module Program

    Private WithEvents myDataGridView As DataGridView

    Private executedFirstTime As Boolean = True

    Sub Main()
        setupDataGridView()
        createForm()
    End Sub

    Private Sub createForm()
        Dim myForm As Form = New Form With {.Text = "VB.NET WinForms : DataGridView - Fill From ArrayList", .ClientSize = New Size(564, 520), .BackColor = Color.CornflowerBlue}
        myForm.Controls.Add(myDataGridView)
        Application.EnableVisualStyles()
        Application.Run(myForm)
    End Sub
    'SETUP OUR DATAGRIDVIEW
    Private Sub setupDataGridView()
        'instantiate the datagridview,passing in locatin,size
        myDataGridView = New DataGridView With {.Location = New Point(30, 70), .Size = New Size(500, 400), .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, .SelectionMode = DataGridViewSelectionMode.FullRowSelect, .ColumnCount = 3}
        'setup datagridview columns
        myDataGridView.Columns(0).Name = "NAME"
        myDataGridView.Columns(1).Name = "CATEGORY"
        myDataGridView.Columns(2).Name = "DISTANCE(Light Years)"
        'populate data
        populateData()

    End Sub
    'SelectionChanged Event Handler.Executed when the DataGridView selection changes.
    Private Sub myDataGridView_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myDataGridView.SelectionChanged
        'don't show messagebox on first selection when we just run the project
        If executedFirstTime Then
            executedFirstTime = False
            Return
        End If

        'You can now select
        Try
            Dim selectedIndex As Integer = myDataGridView.SelectedRows(0).Index
            If selectedIndex <> -1 Then
                If myDataGridView.SelectedRows(0).Cells(0).Value IsNot Nothing Then
                    Dim name As String = myDataGridView.SelectedRows(0).Cells(0).Value.ToString()
                    MessageBox.Show(name)
                End If
            End If
        Catch argumentOutOfRangeException As ArgumentOutOfRangeException
            MessageBox.Show(argumentOutOfRangeException.Message)
        End Try
    End Sub
    'Populate data
    Private Sub populateData()
        Dim nebulae As ArrayList = New ArrayList From {"Horse Head", "Black Widow", "Ghost Head", "Cat's Eye", "Elephant's Trunk", "Helix", "Rosette", "Snake", "Bernad 68", "Ant", "Orion", "Butterfly", "Eagle", "Own", "Ring", "Pelican", "Cone", "Flame", "Witch Head", "Bumerang"}
        Dim nebularCategory As ArrayList = New ArrayList From {"HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS", "DARK NEBULAR"}
        'Pseudo Random Number generator
        Dim r As Random = New Random()
        For Each nebular As String In nebulae
            'pass min and max value in our Next sub routine
            myDataGridView.Rows.Add(nebular, nebularCategory(r.[Next](0, 5)), (r.[Next](9, 9999)).ToString())
        Next
    End Sub
End Module

Explanations.

  1. Fist we add our imports to our project using VB.NET's Imports directive. This will import our required namespaces.

  2. Second we define a method called populateData() to populate our data to our DataGridView.

We first instantiate our ArrayLists using the Collection Initializer syntax:

 Dim nebulae As ArrayList = New ArrayList From {"Horse Head", "Black Widow", "Ghost Head", "Cat's Eye", "Elephant's Trunk", "Helix", "Rosette", "Snake", "Bernad 68", "Ant", "Orion", "Butterfly", "Eagle", "Own", "Ring", "Pelican", "Cone", "Flame", "Witch Head", "Bumerang"}
        Dim nebularCategory As ArrayList = New ArrayList From {"HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS", "DARK NEBULAR"}

Then generate random data using the System.Random() class:

Dim r As Random = New Random()
        For Each nebular As String In nebulae
            'pass min and max value in our Next sub routine
            myDataGridView.Rows.Add(nebular, nebularCategory(r.[Next](0, 5)), (r.[Next](9, 9999)).ToString())
        Next
  1. Then setup our DataGridView by instantiating and setting its properties using the Object initializer syntax.

We then add the dataGridview headers as well:

 Private Sub setupDataGridView()
        'instantiate the datagridview,passing in locatin,size
        myDataGridView = New DataGridView With {.Location = New Point(30, 70), .Size = New Size(500, 400), .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, .SelectionMode = DataGridViewSelectionMode.FullRowSelect, .ColumnCount = 3}
        'setup datagridview columns
        myDataGridView.Columns(0).Name = "NAME"
        myDataGridView.Columns(1).Name = "CATEGORY"
        myDataGridView.Columns(2).Name = "DISTANCE(Light Years)"
        'populate data
        populateData()

    End Sub
  1. We listen to DataGridView SelectionChanged event:

    Private Sub myDataGridView_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myDataGridView.SelectionChanged

    We will show the selected item in a messagebox.

  2. We create our Form by instantiating and setting the From properties.

Then enable visual styles of the application then run the application.

  1. Lastly we have our Main() sub routine to launch our application.

alt

Comments