user9204293
user9204293

Reputation:

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?

Upvotes: 5

Views: 6939

Answers (2)

Here's the code in VB.NET:

Private Sub Owner_idComboBox_DropDown(sender As Object, e As EventArgs) Handles Owner_idComboBox.DropDown
    For Each item In Owner_idComboBox.Items
        Dim tmpLabel As New Label
        tmpLabel.Text = Owner_idComboBox.GetItemText(item)
        tmpLabel.Font = Owner_idComboBox.Font
        If tmpLabel.PreferredSize.Width > Owner_idComboBox.DropDownWidth Then Owner_idComboBox.DropDownWidth = tmpLabel.PreferredSize.Width
    Next
End Sub

Upvotes: 0

Brien Foss
Brien Foss

Reputation: 3367

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

Upvotes: 7

Related Questions