AntonioRodrigo
asked on
ComboBox drop down width when font is bold
Hello,
I am using Windows Forms, Visual Studio 2010.
I have several combo boxes with items longer than the combo is. So I've created a function which makes drop down width wide as the widest string is. Here is my function:
Public Sub WideComboDropDown()
Dim conKontrola As ComboBox
conKontrola = ComboBox2 'in this example I am using ComboBox2. Otherwise, it's
'conKontrola = Me, because whole class inherits ComboBox
If conKontrola.Items.Count > 0 Then
Dim lengthHolding As Int32 = 0
Dim stringWidth As Int32 = 0
Dim g As Graphics = conKontrola.CreateGraphics
'seeking for the longest item
For Each myItem As Object In conKontrola.Items
lengthHolding = g.MeasureString(myItem, conKontrola.Font).Width + 15
If lengthHolding > stringWidth Then
stringWidth = lengthHolding
End If
Next
conKontrola.DropDownWidth = stringWidth + 15 '15 for scroll bar
End Sub
This function works perfect if use unbolded items. When I use bold font, width is not correctly calculated and I don't know what to do about it. Here are snap shots with text unbolded and bolded (I am from Slovenia, so text is Slovene).
Best regards, Frenky
I am using Windows Forms, Visual Studio 2010.
I have several combo boxes with items longer than the combo is. So I've created a function which makes drop down width wide as the widest string is. Here is my function:
Public Sub WideComboDropDown()
Dim conKontrola As ComboBox
conKontrola = ComboBox2 'in this example I am using ComboBox2. Otherwise, it's
'conKontrola = Me, because whole class inherits ComboBox
If conKontrola.Items.Count > 0 Then
Dim lengthHolding As Int32 = 0
Dim stringWidth As Int32 = 0
Dim g As Graphics = conKontrola.CreateGraphics
'seeking for the longest item
For Each myItem As Object In conKontrola.Items
lengthHolding = g.MeasureString(myItem, conKontrola.Font).Width + 15
If lengthHolding > stringWidth Then
stringWidth = lengthHolding
End If
Next
conKontrola.DropDownWidth = stringWidth + 15 '15 for scroll bar
End Sub
This function works perfect if use unbolded items. When I use bold font, width is not correctly calculated and I don't know what to do about it. Here are snap shots with text unbolded and bolded (I am from Slovenia, so text is Slovene).
Best regards, Frenky
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
TextRenderer.MesureText is the method you should use for measuring string sizes in combo boxes.
lengthHolding = g.MeasureString(myItem, conKontrola.Font).Width + 15
to
lengthHolding = g.MeasureString(myItem, New Font(conKontrola.Font, conKontrola.Font.Style)).W