How to manually drop down a DataGridViewComboBoxColumn?

前端 未结 7 1546
清酒与你
清酒与你 2020-12-01 14:20

I have a DataGridView with one DataGridViewComboBoxColumn in my WinForms application. I need to drop down (open) this DataGridViewComboBoxColumn manually, let\'s say after a

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 14:46

    I was looking for an answer to this as well. I ended up writing a generic sub that could be called from any DataGridView since I had plenty in my apps and I wanted them all to behave the same way. This worked well for me so I wanted to share it with anyone else who stumbled across this post.

    In the MouseClick event for the DGV I add the code

    Private Sub SomeGrid_MouseClick(sender As Object, e As MouseEventArgs) Handles SomeGrid.MouseClick
        DGV_MouseClick(sender, e)
    End Sub
    

    Which calls the following sub that I store in a shared module

    Public Sub DGV_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Try
            Dim dgv As DataGridView = sender
            Dim h As DataGridView.HitTestInfo = dgv.HitTest(e.X, e.Y)
            If h.RowIndex > -1 AndAlso h.ColumnIndex > -1 AndAlso dgv.Columns(h.ColumnIndex).CellType Is GetType(DataGridViewComboBoxCell) Then
                Dim cell As DataGridViewComboBoxCell = dgv.Rows(h.RowIndex).Cells(h.ColumnIndex)
                If Not dgv.CurrentCell Is cell Then dgv.CurrentCell = cell
                If Not dgv.IsCurrentCellInEditMode Then
                    dgv.BeginEdit(True)
                    CType(dgv.EditingControl, ComboBox).DroppedDown = True
                End If
            End If
        Catch ex As Exception
        End Try
    End Sub
    

    I never caught any errors, I only include the Try..Catch code for some rare instance I couldn't think of that might throw an exception. I didn't want the user bothered by error messages for this scenario. If the sub fails, then most likely the DGV will just behave like it normally does anyways.

提交回复
热议问题