AndyMC Posted April 7, 2003 Posted April 7, 2003 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 Quote
*Experts* Volte Posted April 7, 2003 *Experts* Posted April 7, 2003 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 Functionto get the longest item in the ComboBox; then just set the DropdownWidth to the value returned. Quote
AndyMC Posted April 8, 2003 Author Posted April 8, 2003 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 Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.