将滚动条添加到WinForms ComboBox

时间:2018-02-01 22:49:53

标签: c# winforms combobox scrollbar

我在Windows窗体应用程序中有一个ComboBox,显示来自MySQL的特定数据。一世  我只是想知道如何将水平滚动条添加到我的ComboBox,因为我的数据太长而无法显示?

2 个答案:

答案 0 :(得分:3)

  

如果使用Windows Presentation Foundation(WPF):

ScrollViewer.HorizontalScrollBarVisibility Property

  

获取或设置一个值,该值指示是否为水平ScrollBar   应该显示。

在此处添加ScrollViewer.HorizontalScrollBarVisibility="Visible"

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

例如:

enter image description here

或者您可以导航到对象的属性并在此处选择:

enter image description here

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

  

如果使用Windows窗体(WinForms):

如果下拉列表的长度是静态的,您只需将DropDownWidth设置为足够大的值即可显示列表的完整长度。

enter image description here

例如,无需调整(文本被截断):

enter image description here

例如,带有调整(显示文字):

enter image description here

如果您需要动态设置宽度,请将以下代码放在DropDown事件处理程序中,或将其设为私有函数/方法调用:

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;

例如,动态宽度:

enter image description here

答案 1 :(得分:0)

这是 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