Search code examples
c#winformscomboboxscrollbar

Add Scrollbar to WinForms ComboBox


I have a ComboBox in Windows Form Application showing specific data from MySQL. I am just wondering how to add horizontal scroll bar to my ComboBox as my data is too long to show?


Solution

  • If working with Windows Presentation Foundation (WPF):

    ScrollViewer.HorizontalScrollBarVisibility Property

    Gets or sets a value that indicates whether a horizontal ScrollBar should be displayed.

    Add ScrollViewer.HorizontalScrollBarVisibility="Visible" here:

    <ComboBox HorizontalAlignment="Left" Margin="60,44,0,0" VerticalAlignment="Top" Width="264" Height="72" ScrollViewer.HorizontalScrollBarVisibility="Visible"/>
    

    For example:

    enter image description here

    Or you can navigate to the Properties of the object and select here:

    enter image description here

    -----------------------------------------------------------

    If working with Windows Forms (WinForms):

    If the length of your dropdowns is static, you can just set the DropDownWidth to a value large enough to display the full length of your list.

    enter image description here

    For example, without adjustments (the text is cut off):

    enter image description here

    For example, with adjustments (the text is shown):

    enter image description here

    If you need to dynamically set the width, either place the following code in your DropDown event handler or make it a private function/method call :

    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 ((ComboBox)sender).Items)
    {
        newWidth = (int)g.MeasureString(s, font).Width
            + vertScrollBarWidth;
        if (width < newWidth)
        {
            width = newWidth;
        }
    }
    senderComboBox.DropDownWidth = width;
    

    For example, with dynamic width:

    enter image description here