组合框项目太长

Isa*_*ron 0 c# combobox winforms

我的组合框中的某些项目长度超过 20 个字符,我编写了此代码以使它们变小并添加“...”,但它\xc2\xb4s 不起作用。\n通过示例而不是“comboboxitemnumberthird”,它看起来像this:"comboboxitemnu..." 以适应组合框的大小

\n\n
i=0;\ndo\n{\n    var item = comboBox1.Items[i].ToString();\n    if (item.Length >= 17) // not sure about this part\n    {\n        item = item.Substring(0, item.Length - 6) + "...";\n    }\n    i++;\n} while (i < comboBox1.Items.Count); //finishes when theres not any other item left on the combobox\n
Run Code Online (Sandbox Code Playgroud)\n\n

请让我知道出了什么问题。提前致谢。

\n

小智 5

只需将此代码粘贴到DropDown的事件中即可ComboBox

 Graphics g = comboBox1.CreateGraphics();
 float largestSize = 0;

 for (int i = 0; i < comboBox1.Items.Count; i++)
 {
     SizeF textSize = g.MeasureString(comboBox1.Items[i].ToString(), comboBox1.Font);
     if (textSize.Width > largestSize)
         largestSize = textSize.Width;
 }

 if (largestSize > 0)
     comboBox1.DropDownWidth = (int)largestSize;
Run Code Online (Sandbox Code Playgroud)