Search code examples
vb.netdatagridviewdatagridviewcolumndatagridviewcomboboxcell

How to set a data grid column to be a drop down when binding to a table


I am able to create a data table and bind it to a datagridview. If possible I want something more sophisticated. I want to limit the first column to values 1 to 12 and the 2nd column to either AM or PM.

Thanks in advance.

        mDataTable = GetTable()

            DataGridView1.DataSource = mDataTable


Function GetTable() As DataTable
        ' Create new DataTable instance.
        Dim table As New DataTable

        ' Create four typed columns in the DataTable.
        table.Columns.Add("Hour", GetType(Integer))
        table.Columns.Add("AM/PM", GetType(String))
        table.Columns.Add("Delete", GetType(Boolean))

        For i = 1 To mSchedules.Count
            table.Rows.Add(SetAMPMHour(mSchedules(i - 1).ScheduleINetHour), SetAMPM(mSchedules(i - 1).ScheduleINetHour), False)

        Next

        Return table
    End Function

Solution

  • If the combobox column is going to have fixed values, you can manually define those values either at design time or at runtime (althought both ways require you to set AutoGenerateColumns property to False before you bind your data to your grid).

    If you want to do it by code, try this:

    DataGridView1.AutoGenerateColumns = False
    Dim hoursCol, timeOfDayCol As New DataGridViewComboBoxColumn
    Dim deleteCol As New DataGridViewCheckBoxColumn
    
    For i As Integer = 1 To 12
        hoursCol.Items.Add(i)
    Next
    timeOfDayCol.Items.Add("AM")
    timeOfDayCol.Items.Add("PM")
    
    hoursCol.DataPropertyName = "Hour"
    timeOfDayCol.DataPropertyName = "AM/PM"
    deleteCol.DataPropertyName = "Delete"
    
    DataGridView1.Columns.Add(hoursCol)
    DataGridView1.Columns.Add(timeOfDayCol)
    DataGridView1.Columns.Add(deleteCol)
    
    mDataTable = GetTable()
    DataGridView1.DataSource = mDataTable
    

    If you want to do it in design time:

    Create your Combobox Column...

    ComboBox Column

    ...set DataPropertyName to the name of the column of the DataTable that will be binded to that GridView column, and in Collection define the values that will populate the ComboBox ComboBox Column Values

    Remember that, even if you define the values in design time, you have to programatically set AutoGenerateColumns to False before you set the data source. Also, if you create a ComboBox Column in design time, you'll have to fill it with String values.