Adjust combobox drop down list width- C#
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
}
}
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
}
}
6 Comments:
Thanks for this, it works perfectly.
I modified it slightly to handle a ToolStripComboBox; these are the needed changes:
ToolStripComboBox senderComboBox = (ToolStripComboBox)sender;
...
Graphics g = senderComboBox.ComboBox.CreateGraphics();
...
foreach (string s in ((ToolStripComboBox)sender).Items)
...
and finally...
g.Dispose();
font.Dispose();
Thanks again:)
Hi, I just wanna ask, can this be use to a DropDownList in web
Thank you very much. It really helped me.
Yep, good piece of code. Thanks a lot for sharing it with us :-)
Keep up.
thanks man this was helpful.
Thanks for both codes
Very useful
Post a Comment
<< Home