C# 如何将 ListBox 中的所有项目打印到 TextBox?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8831858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print all items from ListBox to a TextBox?
提问by HelpNeeder
I want to display all elements from a ListBox to a TextBox. I'm not sure how to do this, I have tried doing foreach statement but it doesn't work for the reason that ListBox doesn't contain IEnumerator.
我想显示从 ListBox 到 TextBox 的所有元素。我不知道该怎么做,我试过做 foreach 语句,但它不起作用,因为 ListBox 不包含 IEnumerator。
How to do this?
这该怎么做?
采纳答案by VS1
The Items collection of Winforms Listbox returns a Collection type of Object so you can use ToString()on each item to print its text value as below:
Winforms Listbox 的 Items 集合返回 Object 的 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;
回答by Obi
Try running your foreach on Listbox.Items..that has an enumerator that you can use
尝试在 Listbox.Items 上运行你的 foreach ......它有一个你可以使用的枚举器
回答by Shai
foreach (ListItem liItem in listBox1.Items)
textBox1.Text += liItem.Value + " "; // or .Text
EDIT:
编辑:
Since you're using WinForms, ListBox.Itemsreturns an ObjectCollection
由于您使用的是 WinForms,因此ListBox.Items返回一个ObjectCollection
foreach (object liItem in listBox1.Items)
textBox1.Text += liItem.ToString() + " "; // or .Text

