Solved

Help setting combobox dropdown list width

Posted on 2016-08-08
4
38 Views
1 Endorsement
Last Modified: 2016-08-13
Hi,


How do you adjust the width of the dropdown list of a combobox based on the size of the text?

Thanks,

Victor
1
Comment
Question by:vcharles
  • 2
  • 2
4 Comments
 
LVL 32

Expert Comment

by:it_saige
ID: 41747884
At it's simplest -

Form1.vb -
Public Class Form1
	ReadOnly items As New List(Of String)({"TEXT", "LONGTEXT", "LONGERTEXT", "LONGESTTEXT", "LONGTEXTTHATISLONGERTHANTHELONGEST"})
	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
		ComboBox1.DataSource = items
		ComboBox2.DataSource = items
		ComboBox3.DataSource = items
		AutoSizeComboBox(ComboBox3)
	End Sub

	Private Sub AutoSizeComboBox(cb As ComboBox)
		Using g As Graphics = cb.CreateGraphics()
			Dim maxWidth = 0.0F
			For Each item In cb.Items
				maxWidth = Math.Max(maxWidth, g.MeasureString(item.ToString(), cb.Font).Width)
			Next
			cb.Width = CType(maxWidth + 20, Integer)
		End Using
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.ComboBox1 = New System.Windows.Forms.ComboBox()
		Me.ComboBox2 = New System.Windows.Forms.ComboBox()
		Me.ComboBox3 = New System.Windows.Forms.ComboBox()
		Me.SuspendLayout()
		'
		'ComboBox1
		'
		Me.ComboBox1.FormattingEnabled = True
		Me.ComboBox1.Location = New System.Drawing.Point(13, 13)
		Me.ComboBox1.Name = "ComboBox1"
		Me.ComboBox1.Size = New System.Drawing.Size(121, 21)
		Me.ComboBox1.TabIndex = 0
		'
		'ComboBox2
		'
		Me.ComboBox2.FormattingEnabled = True
		Me.ComboBox2.Location = New System.Drawing.Point(13, 41)
		Me.ComboBox2.Name = "ComboBox2"
		Me.ComboBox2.Size = New System.Drawing.Size(329, 21)
		Me.ComboBox2.TabIndex = 1
		'
		'ComboBox3
		'
		Me.ComboBox3.FormattingEnabled = True
		Me.ComboBox3.Location = New System.Drawing.Point(13, 69)
		Me.ComboBox3.Name = "ComboBox3"
		Me.ComboBox3.Size = New System.Drawing.Size(121, 21)
		Me.ComboBox3.TabIndex = 2
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(354, 261)
		Me.Controls.Add(Me.ComboBox3)
		Me.Controls.Add(Me.ComboBox2)
		Me.Controls.Add(Me.ComboBox1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)

	End Sub
	Friend WithEvents ComboBox1 As System.Windows.Forms.ComboBox
	Friend WithEvents ComboBox2 As System.Windows.Forms.ComboBox
	Friend WithEvents ComboBox3 As System.Windows.Forms.ComboBox

End Class

Open in new window

Produces the following output -Capture.JPGThe first and second combobox's are hard set to initial size and full form size whereas the third combo box uses the autosize method to resize according to it's items.
Capture.JPG-saige-
1
 

Author Comment

by:vcharles
ID: 41750111
Hi,

Thank you for the code, is there a  way to also set a naximum width when you use autosize?

Victor
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 41750977
Sure, you could do something like:
Public Class Form1
	ReadOnly items As New List(Of String)({"TEXT", "LONGTEXT", "LONGERTEXT", "LONGESTTEXT", "LONGTEXTTHATISLONGERTHANTHELONGEST"})
	Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
		ComboBox1.DataSource = items
		ComboBox2.DataSource = items
		ComboBox3.DataSource = items
		AutoSizeComboBox(ComboBox3, 20)
	End Sub

	Private Sub AutoSizeComboBox(cb As ComboBox, Optional minWidth As Integer = 50)
		Using g As Graphics = cb.CreateGraphics()
			Dim maxWidth = 0.0F
			For Each item In cb.Items
				maxWidth = Math.Max(maxWidth, g.MeasureString(item.ToString(), cb.Font).Width)
			Next
			cb.Width = CType(Math.Min(maxWidth, minWidth) + 20, Integer)
		End Using
	End Sub
End Class

Open in new window

Which now produces the following output (I explicitly chose an extremely small width):Capture.JPG-saige-
0
 

Author Closing Comment

by:vcharles
ID: 41754829
Thank You.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now