My Photo
Name:
Location: Bangalore, India
Google

Tips to Reduce Abdominal Fat!

Tuesday, November 07, 2006

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
}
}

6 Comments:

Blogger beelzeboris said...

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:)

8:37 PM  
Blogger mega_kong said...

Hi, I just wanna ask, can this be use to a DropDownList in web

6:03 PM  
Blogger Rosemary said...

Thank you very much. It really helped me.

9:15 PM  
Blogger F£ö said...

Yep, good piece of code. Thanks a lot for sharing it with us :-)
Keep up.

1:13 AM  
Blogger Brian said...

thanks man this was helpful.

7:39 AM  
Blogger Jerry said...

Thanks for both codes
Very useful

5:42 AM  

Post a Comment

<< Home