Think In Geek

In geek we trust

Full view of ComboBox drop-down list components in C# 3.0

By default in C# 3.0 ComboBox controls don’t provide support for showing drop-down list items if they exceed the width of their parent ComboBox, like this one:

Cropped ComboBox

Cropped ComboBox

This is annoying because users cannot read properly the information. To solve that problem, all we have to do is derive the ComboBox class and override the DropDown event as follows:

public class ComboBoxEx : ComboBox
	public ComboBoxEx()
		: base()
		DropDown += new EventHandler(event_DropDown);
	void event_DropDown(object sender, EventArgs e)
			ComboBox comboBox = (ComboBox)sender; // Catch the combo firing this event
			int width = comboBox.Width; // Current width for ComboBox
			Graphics g = comboBox.CreateGraphics(); // Get graphics for ComboBox
			Font font = comboBox.Font; // Doesn't change original font
			//checks if a scrollbar will be displayed.
			int vertScrollBarWidth;
			if (comboBox.Items.Count > comboBox.MaxDropDownItems)
				//If yes, then get its width to adjust the size of the drop down list.
				vertScrollBarWidth = SystemInformation.VerticalScrollBarWidth;
				//Otherwise set to 0
				vertScrollBarWidth = 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.Items)
				if (s != null)
					newWidth = (int)g.MeasureString(s.Trim(), font).Width + vertScrollBarWidth;
					if (width < newWidth)
						width = newWidth;
			// Finally, adjust the new width
			comboBox.DropDownWidth = width;
		catch {  }

The following picture shows the results of using the above control instead of the default one:

Non Cropped ComboBox

Non Cropped ComboBox

, ,

2 thoughts on “Full view of ComboBox drop-down list components in C# 3.0

  • Gary says:

    Great stuff! Thanks for posting.

  • Purushotham says:

    I am getting an exception(Casting) in the below point
    Exception Details:
    Unable to cast object of type ‘System.Data.DataRowView’ to type ‘System.String’.
    foreach (string s in comboBox.Items)

    Can you help me how to cast it.
    Thanks in Advance……

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    Markdown is turned off in code blocks:
     [This is not a link](

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see

This site uses Akismet to reduce spam. Learn how your comment data is processed.