ComboBox项太长了

时间:2014-09-21 21:55:43

标签: c# winforms combobox

我的组合框中的一些项目长度超过20个字符,我编写了这个代码以使它们更小并添加“...”但它不起作用。 通过示例而不是“comboboxitemnumberthree”它看起来像这样:“comboboxitemnu ...”以适应组合框的大小

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

请告诉我有什么问题。提前谢谢。

3 个答案:

答案 0 :(得分:1)

我不是在我的机器上测试,但这应该做你需要的。尽可能避免做任何事情。为了可维护性。

for (int i = 0; i < combobox.Items.Count; i++) {
    if (combobox.Items[i].ToString().Length > limit) {
        // -3 for the ellipsis
        combobox.Items[i] = String.Format(
            "{0}...", combobox.Items[i].ToString().Substring(0, limit - 3)
        );
    }
}

编辑:修改过的代码。当时在拉斯维加斯。 ; P

答案 1 :(得分:1)

只需将代码粘贴到组合框的下拉事件中即可。

 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;

答案 2 :(得分:0)

截断

后,您没有用新字符串替换组合框中的项目
for(int x = 0; x < combobox.Items.Count; x++)
{
    string item = combobox.Items[x].ToString();
    if(item.Length > 17)
        combobox.Items[x] = item.Substring(0,17) + "...";
}
相关问题