Many people around me have already encountered this problem. What if I want to show longer text in a combobox than the length of this component? A really short code will solve this problem.
I have created a winform with 2 ComboBoxes on it: comboBox1, comboBox2. I use both popular dropdownstyle of ComboBoxes: DropDown and DropDownList. Set both ComboBoxes datasource to an enum in the constructor of the Form:
enum DataContent { First, SecondLine, MyThirdLine, FinallyMyFourthLineIntoTheComboBox } public partial class Form1 : Form { public Form1() { InitializeComponent(); comboBox1.DataSource = Enum.GetValues(typeof(DataContent)); comboBox2.DataSource = Enum.GetValues(typeof(DataContent)); } }
The result is:
Now I create a DropDown event that will make both ComboBoxes subscribe to:
private void comboBoxes_DropDown(object sender, EventArgs e) { Graphics g = (sender as ComboBox).CreateGraphics(); float highest = 0; for (int i = 0; i < (sender as ComboBox).Items.Count; i++) { SizeF textLength = g.MeasureString((sender as ComboBox).Items[i].ToString(), (sender as ComboBox).Font); if (textLength.Width > highest) highest = textLength.Width; } if (highest > 0) (sender as ComboBox).DropDownWidth = (int) highest; }
And the result is the expected: