Wednesday, January 16, 2008

Setting Drop Down width

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.

protected void SetDropDownWidth(object sender, EventArgs e)
{
ComboBox senderComboBox = (ComboBox)sender;
int width = senderComboBox.DropDownWidth;
Graphics g = senderComboBox.CreateGraphics();
Font font = senderComboBox.Font;
int newWidth;
foreach (Object s in senderComboBox.Items)
{
string ss = senderComboBox.GetItemText(s);
newWidth = (int)g.MeasureString(ss, font).Width;
if (width < newWidth) { width = newWidth; }
}
senderComboBox.DropDownWidth = width;
}

No comments: