VB.NET - Introduction to DataGridView

April 10, 2018 Oclemy VB.NET DataGridView, VB.NET Array 5 minutes, 22 seconds

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

DataGridView does provide a powerful, flexible mechanism for rendering tabular data.

DataGridView Array

Tabular form of rendering data is quite popular in many types of software from financial, to inventory to management systems. This makes sense since majority of these data get stored in relational databases. And these databasese normally store data in tables with rows and columns.

DataGridView is powerful in that it allows us to:

  1. read-only to editable views.
  2. small to large datasets.

DataGridView is customizable in that it allows us to extend the DataGridView class to implement custom behaviors and views.

However, it also provides us many pre-existing classes that allow us not reinvent the wheel. These classes can allow us to create custom cell types that can render different types of data like images, boolean and lists of data.

Different data stores can be used to populate a datagridview. However, the datagridview can also be operated without any data source bound to it.

We can just programmatically inside a loop add our rows. This is called unbound mode it has no underlying data store.

DataGridView was introducednas a replacement to the DataGrid control.

Binding data to DataGridView

Binding data to dataGridView is quite easy as in many cases you only have to set the DataSource property.

If your data contains multiple lists or tables, then you can set the DataMember property to a string that specifies the list or table to bind to.

The DataGridView can bind ti instances of classes below:

  1. A class that implements the IList interface, including one dimensional arrays.
  2. A class that implements the IListSource interface. e.g DataTable and DataSet.
  3. A class that implements the IBindingList interface, e.g BindingList.
  4. A class that implements the IBindingListView interface, e.g BindingSoucr.

Data can be bound to the public properties of objects returned by these interfaces or to properties collection returned by an ICustomTypeDescriptor interface, if implemented on the returned objects.

Example 1. - VB.NET Populating DataGridView From Multiple Arrays

Basically each array corresponds to a Column in our datagridview. We'll have three columns, First we populate the nebular names in the first column, the nebular categories in second column and in the third column we generate random integers to use as Nebular distance in light years.


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

Module Program

    Private WithEvents myDataGridView As DataGridView

    Private executedFirstTime As Boolean = True
    ' Main sub routine. setup datagridview first then create the form
    Sub Main()
        setupDataGridView()
        createForm()
    End Sub
    'create form, set its properties and run the application
    Private Sub createForm()
        Dim myForm As Form = New Form With {.Text = "VB.NET WinForms : DataGridView - Fill From Array - Camposha.info", .ClientSize = New Size(564, 520), .BackColor = Color.MediumSeaGreen}
        myForm.Controls.Add(myDataGridView)
        Application.EnableVisualStyles()
        Application.Run(myForm)
    End Sub
    'setup datagridview with column names as well as properties
    Private Sub setupDataGridView()
        myDataGridView = New DataGridView With {.Location = New Point(30, 70), .Size = New Size(500, 400), .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, .SelectionMode = DataGridViewSelectionMode.FullRowSelect, .ColumnCount = 3}
        myDataGridView.Columns(0).Name = "NAME"
        myDataGridView.Columns(1).Name = "CATEGORY"
        myDataGridView.Columns(2).Name = "DISTANCE(Light Years)"
        populateData()
    End Sub

    Private Sub myDataGridView_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myDataGridView.SelectionChanged
        'If we run the form first time don't show the selectedItem 
        If executedFirstTime Then
            executedFirstTime = False
            Return
        End If
        'Now subsequently show selected items in our datagridview
        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()
        'String Arrays
        Dim nebulae As String() = {"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 String() = {"HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS", "DARK NEBULAR"}
        'Random class to generate random distances.
        Dim r As Random = New Random()
        For Each nebular As String In nebulae
            'supply minValue and maxvalue
            myDataGridView.Rows.Add(nebular, nebularCategory(r.[Next](0, 5)), (r.[Next](9, 9999)).ToString())
        Next
    End Sub
End Module

EXPLANATIONS

  1. First we import our namespaces using the Imports directive. In this case we are interested in the System,System.Drawing and System.Windows.Forms namespaces.

    Imports System
    Imports System.Drawing
    Imports System.Windows.Forms
  2. Then we define our Module named Program:

    Module Program
  3. We'll have two instance fields: of type System.Windows.Forms.DataGridView and a Boolean:

    Private WithEvents myDataGridView As DataGridView
    Private executedFirstTime As Boolean = True
  4. We'll have one method called populateData() that will populate our DataGridView with data from several Strings arrays.

Our first array is:

        Dim nebulae As String() = {"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"}

You can see how we define an array in VB.NET. We'll have another array called nebularCategory.

Then we will use the System.Random class to generate random distances:

Private Sub populateData()
        'String Arrays
        Dim nebulae As String() = {"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 String() = {"HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS", "DARK NEBULAR"}
        'Random class to generate random distances.
        Dim r As Random = New Random()
        For Each nebular As String In nebulae
            'supply minValue and maxvalue
            myDataGridView.Rows.Add(nebular, nebularCategory(r.[Next](0, 5)), (r.[Next](9, 9999)).ToString())
        Next
    End Sub
  1. setupDataGridView() will instantiate our dataGridView, set its Location, size, set it Full row select so that when a single cell is clicked we select the whole row as opposed to just selecting a single cell.
    
        myDataGridView = New DataGridView With {.Location = New Point(30, 70), .Size = New Size(500, 400), .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, .SelectionMode = DataGridViewSelectionMode.FullRowSelect, .ColumnCount = 3}
Then we add the datagridview column headers:
```vb
myDataGridView.Columns(0).Name = "NAME"
        myDataGridView.Columns(1).Name = "CATEGORY"
        myDataGridView.Columns(2).Name = "DISTANCE(Light Years)"
  1. createForm() will create for us our Form, add our dataGridView as a control to the Form, enable the visual styles of our application and then run the application.

  2. myDataGridView_SelectionChanged() is an event handler that will handle the myDataGridView.SelectionChanged event. This occurs when the user selects a single item or if an item is selection is made programmatically.

  3. Finally we have our Main() subroutine which launches our application.

Comments