Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-width of ComboBox's content

Does anybody know a way to set the ComboBox's content's width to autosize

I do not mean the ComboBox itself, just the opened content.

like image 704
unicorn Avatar asked Jan 30 '11 09:01

unicorn


2 Answers

You can't use it directly.

Do a trick

First iterate through all items of your combobox, check for the width of every items by assigning the text to a label. Then, check width every time, if width of current item gets greater than previous items then change the maximum width.

int DropDownWidth(ComboBox myCombo) {     int maxWidth = 0;     int temp = 0;     Label label1 = new Label();      foreach (var obj in myCombo.Items)     {         label1.Text = obj.ToString();         temp = label1.PreferredWidth;         if (temp > maxWidth)         {             maxWidth = temp;         }     }     label1.Dispose();     return maxWidth;            }  private void Form1_Load(object sender, EventArgs e) {     comboBox1.DropDownWidth = DropDownWidth(comboBox1); } 

OR

As suggested by stakx, you can use TextRenderer class

int DropDownWidth(ComboBox myCombo) {     int maxWidth = 0, temp = 0;     foreach (var obj in myCombo.Items)     {         temp = TextRenderer.MeasureText(obj.ToString(), myCombo.Font).Width;         if (temp > maxWidth)         {             maxWidth = temp;         }     }     return maxWidth; } 
like image 91
Javed Akram Avatar answered Sep 21 '22 17:09

Javed Akram


obj.ToString() doesn't work for me, I suggest to use myCombo.GetItemText(obj). This works for me:

private int DropDownWidth(ComboBox myCombo) {     int maxWidth = 0, temp = 0;     foreach (var obj in myCombo.Items)     {         temp = TextRenderer.MeasureText(myCombo.GetItemText(obj), myCombo.Font).Width;         if (temp > maxWidth)         {             maxWidth = temp;         }     }     return maxWidth + SystemInformation.VerticalScrollBarWidth; } 
like image 30
user2361362 Avatar answered Sep 21 '22 17:09

user2361362