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

Isaac Bolinger picture Isaac Bolinger · Dec 15, 2010 · Viewed 13.1k times · Source

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?

Answer

Nemanja Vujacic picture Nemanja Vujacic · Jul 19, 2012

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#