2012-01-12 44 views
1

我想顯示列表框中的所有元素到文本框。我不知道如何做到這一點,我試圖做foreach語句,但它不起作用的原因是ListBox不包含IEnumerator。如何將列表框中的所有項目打印到文本框?

如何做到這一點?

+0

您是否試過ListBox.Items? – 2012-01-12 08:17:48

+2

[ListBox](http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.listbox.aspx)或[ListBox](http://msdn.microsoft.com/zh-cn/我們/庫/ system.windows.forms.listbox.aspx),我的意思是WebForms或WinForms? – 2012-01-12 08:18:54

+0

這很簡單:只需要​​循環ListViewItems集合並生成字符串,然後在textBox中顯示此字符串。 – Disposer 2012-01-12 08:26:52

回答

6

Winforms Listbox的Items集合返回一個Collection對象的集合類型,因此您可以在每個項目上使用ToString()來打印其文本值如下:

string text = ""; 
foreach(var item in yourListBox.Items) 
{ 
    text += item.ToString() + "/n"; // /n to print each item on new line or you omit /n to print text on same line 
} 
yourTextBox.Text = text; 
+0

這很好地工作。謝謝。 – HelpNeeder 2012-01-12 09:13:33

1

嘗試在Listbox.Items..that運行你的foreach具有您可以使用

2
foreach (ListItem liItem in listBox1.Items) 
    textBox1.Text += liItem.Value + " "; // or .Text 

編輯枚舉:

由於您使用的WinForms,ListBox.Items返回ObjectCollection

foreach (object liItem in listBox1.Items) 
    textBox1.Text += liItem.ToString() + " "; // or .Text 
+0

它似乎沒有工作。 ListItems導致錯誤。當我更改爲ListBox時,liItem.Value會導致錯誤。 – HelpNeeder 2012-01-12 08:21:01

+0

@HelpNeeder沒有幫到你,你又有什麼新錯誤? – Shai 2012-01-12 08:21:53

+0

我得到:無法找到類型或名稱空間名稱'ListItem'(您是否缺少使用指令或程序集引用?) – HelpNeeder 2012-01-12 08:24:33

相關問題