Search code examples
vb.netdatagridviewdatagridviewcomboboxcell

DataGridViewComboBoxCell won't drop


I'm using vb.NET in Visual Studio 2010. I found an example of how to add a ComboBox to a DataGridView cell, and I added it to my code. When I run the code, and I add a new row, the ComboBox is visible, but it has no value displayed in it and it won't drop down.

Have I missed something from the code? Does the DataGridView need to have certain properties set?

dgvFiles.Rows.Add({"Cell1","Cell2"})
Dim gridComboBox As New DataGridViewComboBoxCell
gridComboBox.Items.Add("A") 'Populate the Combobox
gridComboBox.Items.Add("B") 'Populate the Combobox
gridComboBox.Items.Add("C") 'Populate the Combobox
dgvFiles(2, dgvFiles.Rows.Count - 1) = gridComboBox

Edit:

I had set four columns at design time, that wasn't the issue. The issue turned out to be that I had set the DataGridView to 'EditProgrammatically'. I had changed it to that initially to stop users from editing the text cells, but apparently, it prevented the ComboBoxes from dropping.

I appreciate all the answers given. My apologies that I forgot to mention that I had set four columns in design time, and that this issue was caused by me not realising the EditProgrammatically setting had this effect.


Solution

  • Your code is almost fine. Everything drops down. You could have the default value displayed on your list.

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            dgvfiles.Columns.Add("Column1", "Column 1")
            dgvfiles.Columns.Add("Column2", "Column 2")
            dgvfiles.Columns.Add("Column3", "Column 3")
            dgvfiles.Columns.Add("Column4", "Column 4")
            dgvfiles.Rows.Add({"Cell1", "Cell2"})
            Dim gridComboBox As New DataGridViewComboBoxCell
            gridComboBox.Items.Add("A") 'Populate the Combobox
            gridComboBox.Items.Add("B") 'Populate the Combobox
            gridComboBox.Items.Add("C") 'Populate the Combobox
            gridComboBox.Value = gridComboBox.Items(0)
            dgvfiles(2, dgvfiles.Rows.Count - 2) = gridComboBox
        End Sub
    
        Private Sub dgvfiles_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles dgvfiles.CellBeginEdit
            If e.ColumnIndex = 2 Then
                'Do something
            Else
                e.Cancel = True
            End If
        End Sub
    

    enter image description here