VB.NET DataGridView - Add ComboBox Column

July 4, 2017 Oclemy VB.NET DataGridView, VB.NET ComboBox 1 minute, 12 seconds

VB.NET DataGridView - Add ComboBox Column

DataGridView can be used to display several types of data. These different types shall correspond to different DataGridView columns.

Obviously, when you bind a datagridview column to a DataSource. It shall automatically generate for you column types corresponding to the type of data that its reading. Take note that this is the case as long as AutoGenerateColumns property of DataGridView control is set to true.

 DataGridViewComboBoxColumn

  • Show drop down lists in cells.
  • Is data bound, yes. But manual binding.
  • To use combo box columns, you must create them manually and add them to the collection returned by the Columns property.
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())

        'ADD 2ND ROW
        row = New ArrayList
        row.Add("2")
        row.Add("Man cITY")
        row.Add("80")
        DataGridView1.Rows.Add(row.ToArray())

        'ADD 2ND ROW
        row = New ArrayList
        row.Add("3")
        row.Add("Chelsea")
        row.Add("78")
        DataGridView1.Rows.Add(row.ToArray())

        ''ADD COMBOBOX COLUMN
        Dim combo As DataGridViewComboBoxColumn = New DataGridViewComboBoxColumn
        combo.HeaderText = "Year Won"
        combo.Name = "MyCombo"
        combo.Items.Add("2015")
        combo.Items.Add("2014")
        combo.Items.Add("2013")
        combo.Items.Add("2012")
        DataGridView1.Columns.Add(combo)

    End Sub

End Class

Best regards.

Comments