WindowsForms ComboBox Auto DropDownList Width
On a project I'm working on, I use some ComboBoxes that act as a breadcrumb control for a Wizard that I wrote, so the user can jump throughout the wizard to different steps easily and understand where they are. Unfortunately, the ComboBoxes are dynamically filled from an admin section and can be anywhere from a few characters to a few hundred characters. This would make the ComboBoxes very wide. Unfortunately, the ComboBox doesn't automatically change the DropDownWidth Property based off of the items in the ComboBox. I went ahead and wrote a Method to do that (This could be added into an inherited ComboBox to be used over and over too if you wanted) and thought I'd share:
VB
Private Sub FindWidthForDropDown(ByVal ComboBox As ComboBox)
Dim g As Graphics = ComboBox.CreateGraphics()
Dim IsDatabound As Boolean = Not ComboBox.DataSource Is Nothing AndAlso ComboBox.DisplayMember <> ""
Dim WidestWidth As Integer = ComboBox.DropDownWidth
Dim ValueToMeasure As String
Dim CurrentWidth As Integer For i As Integer = 0 To ComboBox.Items.Count - 1
If IsDatabound Then
ValueToMeasure = DirectCast(DirectCast(ComboBox.Items(i), DataRowView)(ComboBox.DisplayMember), String)
Else
ValueToMeasure = DirectCast(ComboBox.Items(i), String)
End If
CurrentWidth = CType(g.MeasureString(ValueToMeasure, ComboBox.Font).Width, Integer)
If CurrentWidth > WidestWidth Then WidestWidth = CurrentWidth
Next
ComboBox.DropDownWidth = WidestWidth
g.Dispose()
End Sub
C#
private void findWidthForDropDown(ComboBox comboBox)
{
bool isDatabound = comboBox.DataSource != null && comboBox.DisplayMember != null && comboBox.DisplayMember != "";
int widestWidth = comboBox.DropDownWidth;
string valueToMeasure;
int currentWidth; using (Graphics g = comboBox.CreateGraphics())
{
for (int i = 0; i < comboBox.Items.Count; i++)
{
if (isDatabound)
valueToMeasure = (string)((DataRowView)comboBox.Items[i])[comboBox.DisplayMember];
else
valueToMeasure = (string)ComboBox.Items[i];
currentWidth = (int)g.MeasureString(valueToMeasure, comboBox.Font).Width;
if (currentWidth > widestWidth) {widestWidth = currentWidth;}
}
}
comboBox.DropDownWidth = widestWidth;
}
Simple, but hopefully helpful. Just pass in the ComboBox and watch it's DropDownWidth change.
UPDATE: Check out the comments for some additional things to add to this method suggested by commenter(s).