ComboBox with dynamic DropDownWidth

AndyMC

Newcomer
Joined
Feb 12, 2003
Messages
10
Hello there,

does anybody know, how to set the DropDownWidth of a ComboBox to dynamically have the optimal width - adjustet to the longest entry?
Meaning that every entry of the list can be read - regardless of the length of the entries?

Thanks for help
Andy
 
You might try using a function like this:
Visual Basic:
    Private Function GetLongestItemWidth(ByVal combo As ComboBox) As Integer
        Dim longest As Integer
        Dim str As String
        Dim g As Graphics = Graphics.FromImage(New Bitmap(1, 1))

        'Enumerate the items in the combo
        For Each str In combo.Items
            Dim wid As Integer

            'Get the width of the item; if it's longer than the
            'longest one so far, store it.
            wid = g.MeasureString(str, combo.Font).Width
            If wid > longest Then longest = wid
        Next

        Return longest
    End Function
to get the longest item in the ComboBox; then just set the DropdownWidth
to the value returned.
 
Thanks for your reply. It works perfectly, except that we use a DataTable that is bound to the ComboBox.

Because of that I had to slightly change your code:

Visual Basic:
Private Function GetLongestItemWidth() As Integer
        Dim longest As Integer
        Dim str As String
        Dim g As Graphics = Graphics.FromImage(New Bitmap(1, 1))
        Dim width As Integer
        Dim myDataRowView As DataRowView


        'Enumerate the items in the combo
        For Each myDataRowView In Me.Items
            str = CStr(myDataRowView.Item(1))
            'Get the width of the item; if it's longer than the
            'longest one so far, store it.
            width = CInt(g.MeasureString(str, Me.Font).Width)
            If width > longest Then longest = width
        Next

        Return longest
    End Function

Thanks again
Andy
 
Back
Top