【问题标题】:How to print all items from ListBox to a TextBox?如何将 ListBox 中的所有项目打印到 TextBox?
【发布时间】:2012-01-12 08:14:41
【问题描述】:

我想显示从 ListBox 到 TextBox 的所有元素。我不知道该怎么做,我试过做 foreach 语句,但它不起作用,因为 ListBox 不包含 IEnumerator。

如何做到这一点?

【问题讨论】:

  • 你试过 ListBox.Items 吗?
  • ListBoxListBox,我是指 WebForms 还是 WinForms?
  • 这很简单:您只需要循环 ListViewItems 集合并构建字符串,然后在 textBox 中显示此字符串。
  • @Disposer: ListViewItems 即使是 ListBox 而不是 ListView?

标签: c# winforms listbox


【解决方案1】:

Winforms Listbox 的 Items 集合返回一个 Collection 类型的 Object,因此您可以在每个项目上使用 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;

【讨论】:

    【解决方案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
    

    【讨论】:

    • 它似乎不起作用。 ListItems 导致错误。当我更改为 ListBox 时, liItem.Value 会导致错误。
    • @HelpNeeder 没有让您正确,您的新错误又是什么?
    • 我得到:找不到类型或命名空间名称“ListItem”(您是否缺少 using 指令或程序集引用?)
    【解决方案3】:

    尝试在 Listbox.Items.. 上运行你的 foreach,它有一个你可以使用的枚举器

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 2021-01-23
      • 2016-04-29
      相关资源
      最近更新 更多