Reputation:
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
Reputation: 1
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
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:
Or you can navigate to the Properties of the object and select 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.
For example, without adjustments (the text is cut off):
For example, with adjustments (the text is shown):
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:
Upvotes: 7