2008年7月3日 星期四

自動調整ComboBox寬度

Q:如何自動調整ComboBox寬度, 使其下拉自動展為最適合寬度?

A:加一ComboBox事件如下
Private Sub ComboBox1_DropDown(ByVal sender As Object, ByVal e As System.EventArgs)_
Handles ComboBox1.DropDown
Dim senderComboBox As ComboBox = DirectCast(sender, ComboBox)
Dim width As Integer = senderComboBox.DropDownWidth
Dim g As Graphics = senderComboBox.CreateGraphics()
Dim font As Font = senderComboBox.Font
Dim vertScrollBarWidth As Integer = _
IIf((senderComboBox.Items.Count > senderComboBox.MaxDropDownItems), _
SystemInformation.VerticalScrollBarWidth, 0)

Dim newWidth As Integer
For Each s As String In DirectCast(sender, ComboBox).Items
newWidth = CInt(g.MeasureString(s, font).Width) + vertScrollBarWidth
If width < width =" newWidth" dropdownwidth =" width" graphics =" senderComboBox.ComboBox.CreateGraphics()

沒有留言: