VB.NET DataGridView - Hide or Show Rows and Columns

July 7, 2017 Oclemy VB.NET DataGridView 1 minute, 25 seconds

DataGridView is one of the most highly configurable and extensible components you’ll generally come across. In a high level that is.While still easy to use. It enables us do this by providing several methods, properties and events to customize the appearance and behavior.

DataGridView can display untyped data like one-dimensional array to typed data like a DataSet.

For us,In this tutorial we see how to programmatically show or hide rows or columns on button click in vb.net winforms.

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        updateDG()
    End Sub

    Private Sub updateDG()
        'ADD COLUMN
        DataGridView1.ColumnCount = 3
        DataGridView1.Columns(0).Name = "Position"
        DataGridView1.Columns(1).Name = "Team"
        DataGridView1.Columns(2).Name = "Points"

        'ADD ROWS
        Dim row As ArrayList = New ArrayList
        row.Add("1")
        row.Add("Man Utd")
        row.Add("82")
        DataGridView1.Rows.Add(row.ToArray())

        '2nd row
        row = New ArrayList
        row.Add("2")
        row.Add("Man City")
        row.Add("80")
        DataGridView1.Rows.Add(row.ToArray())

        '3rd row
        row = New ArrayList
        row.Add("3")
        row.Add("Chelsea")
        row.Add("78")
        DataGridView1.Rows.Add(row.ToArray())

        Dim combo As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn()
        combo.HeaderText = "Year Won"
        combo.Name = "combo"
        combo.Items.Add("2015")
        combo.Items.Add("2014")
        combo.Items.Add("2013")
        DataGridView1.Columns.Add(combo)

    End Sub

    Private Sub hideColumnBtn_Click(sender As Object, e As EventArgs) Handles hideColumnBtn.Click
        DataGridView1.Columns(0).Visible = False

    End Sub

    Private Sub showColumnBtn_Click(sender As Object, e As EventArgs) Handles showColumnBtn.Click
        DataGridView1.Columns(0).Visible = True
    End Sub

    Private Sub hideRowBtn_Click(sender As Object, e As EventArgs) Handles hideRowBtn.Click
        DataGridView1.Rows(0).Visible = False
    End Sub

    Private Sub showRowBtn_Click(sender As Object, e As EventArgs) Handles showRowBtn.Click
        DataGridView1.Rows(0).Visible = True
    End Sub
End Class

Comments