DataGridViewComboBoxColumn: limit MaxDropDownItems

2019-02-26 05:06发布

问题:

I would like to know how to limit the number of items to show in DataGridViewComboBoxColumn. In simple ComboBox we can do it as:

comboBox1.IntegralHeight = false; //this is necessary to make it work!!!
comboBox1.MaxDropDownItems = 3;

But how to do the same in DGVs comboBox`?

When creating ComboBoxColumn there is no IntegralHeight property.

回答1:

I have figured it out by my self, by subscribing to DataGridViewEditControlShowing event, and with this code inside of it:

private void dataGridView1_EditingControlShowing(
    object sender, 
    DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox cb = e.Control as ComboBox;
    if (cb != null)
    {
        cb.IntegralHeight = false;
        cb.MaxDropDownItems = 10;
    }
}

Now the dropdown menu works, it shows as many rows as set for the MaxDropDownItems property.

For Visual Basic

Private Sub dgvDesp_EditingControlShowing( _
    sender As Object, _
    e As DataGridViewEditingControlShowingEventArgs) Handles dgvDesp.EditingControlShowing
    Dim cb As ComboBox = e.Control
    If cb.Items.Count > 0 Then
        cb.IntegralHeight = False
        cb.MaxDropDownItems = 10
    End If
End Sub