【问题标题】:ComboBox item too long组合框项目太长
【发布时间】:2014-11-15 20:10:21
【问题描述】:

我的组合框中的某些项目超过 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

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

【问题讨论】:

    标签: c# winforms combobox


    【解决方案1】:

    我不在我的机器上进行测试,但这应该可以满足您的需求。尽可能避免 do-while。为了可维护性。

    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

    【讨论】:

    • 由于其他原因无法正常工作。您不能更改 foreach 中使用的迭代器。项目在这里是只读的。
    • @Isaac:在这种情况下,您应该避免使用do while,因为普通的for (var i = 0...) 循环更简单。
    • @Dan 是的,我知道,但是当我重新研究我的代码时,这样做对我来说更好理解,我认为调试需要更长的时间
    【解决方案2】:

    您不会在截断后用新字符串替换组合框中的项目

    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) + "...";
    }
    

    【讨论】:

    • 这行得通,我想用另一种方式做,但它行得通,谢谢
    • 您的 do..while 循环似乎是正确的,只需将对 item 的分配替换为对 combobox.Items[i] 的分配即可。 for..loop 比 do...while 更紧凑
    【解决方案3】:

    只需将此代码粘贴到ComboBoxDropDown 事件中即可。

     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;
    

    【讨论】:

      猜你喜欢
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多