I have written the two below methods to auto size the dropdown widths of all the combo boxes on a windows form. However, it doesn’t appear to be hitting any of the combo boxes. When I apply the method ComboBoxDropDownWidth to a single combo box under the form load event it works. To confirm, I also fire ComboBoxAutofitDropDownWidth(this)
under the form load event.
public static int ComboBoxDropDownWidth(ComboBox comboBox)
{
int maxWidth = 0;
foreach (var obj in comboBox.Items)
{
int defaultWidth = TextRenderer.MeasureText(obj.ToString(), comboBox.Font).Width;
if (defaultWidth > maxWidth)
{
maxWidth = defaultWidth;
}
}
return maxWidth;
}
public static void ComboBoxAutofitDropDownWidth(Form form)
{
var comboBoxes = form.Controls
.OfType<ComboBox>();
foreach (var comboBox in comboBoxes)
{
comboBox.DropDownWidth = ComboBoxDropDownWidth(comboBox);
}
}