Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the ComboBox drop down list resize itself to fit the largest item?

I've got a DataGridView with a ComboBox in it that might contain some pretty large strings. Is there a way to have the drop down list expand itself or at least wordwrap the strings so the user can see the whole string without me having to resize the ComboBox column width?

like image 528
Isaac Bolinger Avatar asked Dec 15 '10 09:12

Isaac Bolinger


1 Answers

This is very elegant solution:

private void AdjustWidthComboBox_DropDown(object sender, System.EventArgs e)
{
    ComboBox senderComboBox = (ComboBox)sender;
    int width = senderComboBox.DropDownWidth;
    Graphics g = senderComboBox.CreateGraphics();
    Font font = senderComboBox.Font;
    int vertScrollBarWidth = 
        (senderComboBox.Items.Count>senderComboBox.MaxDropDownItems)
        ?SystemInformation.VerticalScrollBarWidth:0;

    int newWidth;
    foreach (string s in senderComboBox.Items)
    {
        newWidth = (int) g.MeasureString(s, font).Width 
            + vertScrollBarWidth;
        if (width < newWidth )
        {
            width = newWidth;
        }
    }
    senderComboBox.DropDownWidth = width;
}

Adjust combo box drop down list width to longest string width http://www.codeproject.com/KB/combobox/ComboBoxAutoWidth.aspx

Source: Calculating ComboBox DropDownWidth in C#

like image 63
Nemanja Vujacic Avatar answered Sep 28 '22 00:09

Nemanja Vujacic