2014-09-21 142 views
0

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

请让我知道什么是错的大小。提前致谢。

回答

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

+0

它不工作,但为什么我应该避免做什么? – 2014-09-21 22:13:47

+2

这不能用于其他原因。你不能改变在foreach中使用的迭代器。项目在这里只读。 – Steve 2014-09-21 22:18:53

+0

@Isaac:在这种情况下,你应该避免使用'do while',因为正常的'for(var i = 0 ...)'循环更简单。 – 2014-09-21 22:21:28

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

这个工程,我想以另一种方式做,但它的工作原理,谢谢 – 2014-09-21 22:26:56

+0

你做.. while循环看起来是正确的,只需用assoblement替换指定的项目到combobox.Items [i]。 for..loop比do ...更紧凑 – Steve 2014-09-21 22:30:02

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;