2014-11-21 71 views
3

我想列出所有組合框項目在一個消息框中。但我得到的是每個項目都出現在它自己的消息框中。我知道消息框需要在循環之外,但是當我這樣做時,它說變量是未分配的。任何幫助都會很棒。在一個消息框中列出所有組合框項目

私人無效displayYachtTypesToolStripMenuItem_Click(對象發件人,EventArgs的) {

 string yachtTypesString; 

     for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++) 

     { 
      yachtTypesString=typeComboBox.Items[indexInteger].ToString(); 
      MessageBox.Show(yachtTypesString); 
     } 

     } 
+0

問題是你需要assing **串yachtTypesString; **在你的情況下,空字符串**字符串yachtTypesString值=「」; **,也將努力 – Vajura 2014-11-21 07:17:30

回答

0

試試這個

  string yachtTypesString=""; 

    for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++) 

    { 
     yachtTypesString=yachtTypesString + typeComboBox.Items[indexInteger].ToString(); 

    } 

    MessageBox.Show(yachtTypesString); 
+1

你會浪費大量的字符串實例,使用字符串生成器來處理像這樣的過程。 – DevEstacion 2014-11-21 07:05:08

+0

謝謝大家,這裏工作,我只需要添加一個Environment.NewLine,所以他們都會顯示在一個新的行。 – llerdal 2014-11-21 14:24:44

3

像這樣做,

StringBuilder yachtTypesString = new StringBuilder(); 
    for (int indexInteger = 0; indexInteger < typeComboBox.Items.Count; indexInteger++) 
    { 
     yachtTypesString.AppendLine(typeComboBox.Items[indexInteger].ToString()); 
    } 
    MessageBox.Show(yachtTypesString.ToString()); 

注意:不要做字符串用字符串連接,使用StringBuilder對象作爲字符串創建一個新實例。

+0

由於最後一個'yachtTypesString.AppendLine'增加了Carrige返回值,因此'MessageBox'的底部會有一個*空行* – 2014-11-21 07:18:42

1

您可以嘗試使用的Linq

MessageBox.Show(String.Join(Environment.NewLine, typeComboBox.Items.Cast<String>())); 

,並讓它爲你做所有

0

列表中的所有組合框項目的工作在一個信息框

請與下面代碼以獲得Combobox all Text

private void Form1_Load(object sender,EventArgs e) { DataTable dtcheck = new DataTable(); dtcheck.Columns.Add(「ID」); dtcheck.Columns.Add(「Name」); (int i = 0; i < = 15; i ++) { dtcheck.Rows.Add(i,「A」+ i); }

 comboBox1.ValueMember = "ID"; 
     comboBox1.DisplayMember = "Name"; 
     comboBox1.DataSource = dtcheck; 


    } 
} 

    private void button1_Click(object sender, EventArgs e) 
    { 

     string MessageText = string.Empty; 

     foreach(object item in comboBox1.Items) 
     { 
      DataRowView row = item as DataRowView; 

      MessageText += row["Name"].ToString() + "\n"; 
     } 

     MessageBox.Show(MessageText, "ListItems", MessageBoxButtons.OK,MessageBoxIcon.Information); 
    } 
相關問題