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)
	{
		try
		{
			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;
			}
			else
			{
				//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

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

, ,

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

  • Gary says:

    Great stuff! Thanks for posting.

  • Purushotham says:

    Hi,
    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 *