我想顯示列表框中的所有元素到文本框。我不知道如何做到這一點,我試圖做foreach語句,但它不起作用的原因是ListBox不包含IEnumerator。如何將列表框中的所有項目打印到文本框?
如何做到這一點?
我想顯示列表框中的所有元素到文本框。我不知道如何做到這一點,我試圖做foreach語句,但它不起作用的原因是ListBox不包含IEnumerator。如何將列表框中的所有項目打印到文本框?
如何做到這一點?
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;
這很好地工作。謝謝。 – HelpNeeder 2012-01-12 09:13:33
嘗試在Listbox.Items..that運行你的foreach具有您可以使用
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
它似乎沒有工作。 ListItems導致錯誤。當我更改爲ListBox時,liItem.Value會導致錯誤。 – HelpNeeder 2012-01-12 08:21:01
@HelpNeeder沒有幫到你,你又有什麼新錯誤? – Shai 2012-01-12 08:21:53
我得到:無法找到類型或名稱空間名稱'ListItem'(您是否缺少使用指令或程序集引用?) – HelpNeeder 2012-01-12 08:24:33
您是否試過ListBox.Items? – 2012-01-12 08:17:48
[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
這很簡單:只需要循環ListViewItems集合並生成字符串,然後在textBox中顯示此字符串。 – Disposer 2012-01-12 08:26:52