VB.NET DataGridView - Fill from HashSet


A HashSet is generic collection that represents a set of values.

While a datagridview is windows froms components that displays items in a customized grid. A HashSet is defined in the System.Colletions.Generic namespace and is generic.

In this class we see how to work with both, with the hashset being our component.

If you prefer a vide tutorial check here:

What is a HashSet?

The HashSet class is a set collection that implements the ICollection interface and the ICollection generic interface.

The HashSet class implements the ISet class as from .NET 4.0.

This class provides high-performance set operations similar to accessing the keys of the Dictionary<TKey, TValue> or Hashtable collections. In simple terms, the HashSet class can be thought of as a Dictionary<TKey, TValue> collection without values.

Normall A HashSet has no duplicate members.You don;t use indices with a HashSet, only enumerators.

Here's the API definition of a HashSet in VB.NET:

Public Class HashSet(Of T)
    Implements ICollection(Of T), IEnumerable(Of T), IEnumerable, ISerializable,
    IDeserializationCallback, ISet(Of T), IReadOnlyCollection(Of T)

The HashSet is our data source and we want to read its data and populate a datagridview. We create a subroutine called populateData that does that for us:

 Private Sub populateData()
        Dim nebulae As HashSet(Of String) = New HashSet(Of String) 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 HashSet(Of String) = New HashSet(Of String) From {"HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS", "DARK NEBULAR"}
        Dim r As Random = New Random()
        For Each nebular As String In nebulae
            myDataGridView.Rows.Add(nebular, nebularCategory.ToArray()(r.[Next](0, 5)), (r.[Next](9, 9999)).ToString())
        Next
    End Sub

We then get the item that's been clicked and show in a messagebox:


    Private Sub myDataGridView_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myDataGridView.SelectionChanged
        If executedFirstTime Then
            executedFirstTime = False
            Return
        End If

        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

Here's the full source code.

Module1.vb

Here's the full source code:

Imports System
Imports System.Collections.Generic
Imports System.Drawing
Imports System.Linq
Imports System.Windows.Forms
Module Module1

    Private WithEvents myDataGridView As DataGridView
    Private executedFirstTime As Boolean = True

    Private Sub createForm()
        Dim myForm As Form = New Form With {.Text = "VB.NET WinForms : DataGridView - Fill From HashSet - Camposha.info", .ClientSize = New Size(564, 520), .BackColor = Color.DodgerBlue}
        myForm.Controls.Add(myDataGridView)
        Application.EnableVisualStyles()
        Application.Run(myForm)
    End Sub
    Private Sub populateData()
        Dim nebulae As HashSet(Of String) = New HashSet(Of String) 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 HashSet(Of String) = New HashSet(Of String) From {"HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS", "DARK NEBULAR"}
        Dim r As Random = New Random()
        For Each nebular As String In nebulae
            myDataGridView.Rows.Add(nebular, nebularCategory.ToArray()(r.[Next](0, 5)), (r.[Next](9, 9999)).ToString())
        Next
    End Sub
    Private Sub setupDataGridView()
        myDataGridView = New DataGridView With {.Location = New Point(30, 70), .Size = New Size(500, 400), .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill, .SelectionMode = DataGridViewSelectionMode.FullRowSelect, .ColumnCount = 2}
        myDataGridView.Columns(0).Name = "NAME"
        myDataGridView.Columns(1).Name = "CATEGORY"
        populateData()
    End Sub

    Private Sub myDataGridView_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myDataGridView.SelectionChanged
        If executedFirstTime Then
            executedFirstTime = False
            Return
        End If

        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

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

Result DataGridView HashSet

Best regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post