Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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

  • *Experts*
Posted

You might try using a function like this:

    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.

Posted

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:

 

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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...