This method is to adjust combobox drop down list width to longest string width in the list. Combobox menu width increases to longest string in the list. Invoke this method in the DropDown event of combobox.
public static void SetComboScrollWidth(object sender)
{
try
{
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.Width;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
//checks if a scrollbar will be displayed.
//If yes, then get its width to adjust the size of the drop down list.
int vertScrollBarWidth =
(senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
? SystemInformation.VerticalScrollBarWidth : 0;
//Loop through list items and check size of each items.
//set the width of the drop down list to the width of the largest item.
int newWidth;
foreach (string s in ((ComboBox)sender).Items)
{
if (s != null)
{
newWidth = (int)g.MeasureString(s.Trim(), font).Width
+ vertScrollBarWidth;
if (width < newWidth)
{
width = newWidth;
}
}
}
senderComboBox.DropDownWidth = width;
}
catch (Exception objException)
{
//Catch objException
}
}