How to adjust the drop down width of ComboBox?

5 10 2008


Combobox is good, because they utilize less space and at the same time they can show a list of options. But did you noticed one thing? By default the dropdown width of combobox is same as the width of combobox itself. If you add a loooong string to combobox, it will be displayed partially in the drop down list. So how to stretch the with of dropdown list of combobox?


If you are using MFC, you could use the api – CComboBox::SetDroppedWidth() or else you could use the message CB_SETDROPPEDWIDTH. First of all you’ve to iterate all strings in the combobox list and find out the required width. Then set the new drop down width of combobox. See the MFC code snippet for doing so. Code snippet is taken from MSDN and has been modified appropriately.

void CComboBoxDemoDlg::AdjustDropDownWidth()
{
    // Find the longest string in the combo box.
    CComboBox* pComboBox =
        ( CComboBox* ) GetDlgItem( IDC_CMB_STRINGS );
    int MaxWidth = 0;
    CDC* pDC = pComboBox->GetDC();

    // Iterate through all strings in Combobox and get MaxWidth
    CString String;
    CSize TextSize;
    for ( int Index = 0; Index < pComboBox->GetCount(); Index++ )
    {
        // Get n'th string.
        pComboBox->GetLBText( Index, String );

        // Get TextExtend
        TextSize = pDC->GetTextExtent( String );

        // Get MaxWidth.
        if( TextSize.cx > MaxWidth )
        {
            MaxWidth = TextSize.cx;
        }
    }

    pComboBox->ReleaseDC( pDC );

    // Adjust the width for the vertical scroll bar and
    // the left and right border.
    MaxWidth += ::GetSystemMetrics(SM_CXVSCROLL) +
                2 * ::GetSystemMetrics(SM_CXEDGE);

    // Set the dropdown width of combobox.
    pComboBox->SetDroppedWidth( MaxWidth );
}


You could achieve the same by sending CB_SETDROPPEDWIDTH by using SendMessage().


Targeted Audience – Intermediate.

Advertisements