2014-09-21 39 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;