首页 > 解决方案 > Is there a way to display items from an array on separate lines of a TextBox?

问题描述

I have added the items from a checkbox into listbox named displayBurgerBox then into an array. Now I want to display each order (array) on a separate line of a textbox when i click a button. I am getting this text in the box instead of the order System.Windows.Forms.ListBox+ObjectCollection. Any ideas, or should I use a different approach.

private void addItem_Click(object sender, EventArgs e)
{
    string[] listOfItems = new string[1000];
    int numberOfItems = 0;

    listOfItems[numberOfItems] = Convert.ToString(displayBurgerBox.Items);

    orderList.AppendText(listOfItems[numberOfItems]);
    orderList.AppendText(Environment.NewLine);
    MessageBox.Show(listOfItems[numberOfItems]);
}

标签: c#

解决方案


问题在于以下行。

Convert.ToString(displayBurgerBox.Items);

相反,你应该

displayBurgerBox.Items.Cast<String>().ToArray()

另外,我建议您不要预先声明固定大小的数组,而是使用

var listOfItems= displayBurgerBox.Items.Cast<String>().ToArray()

最后,您可以使用 concat 数组

string.Join($"{Environment.NewLine}",listOfItems)

您共享的示例中的最终代码如下所示。

private void addItem_Click(object sender, EventArgs e)
{
        var listOfItems = displayBurgerBox.Items.Cast<String>().ToArray();
        MessageBox.Show(string.Join($"{Environment.NewLine}",listOfItems));
        textBox1.Text = string.Join($"{Environment.NewLine}", listOfItems);
 }

PS:您曾提到要将其添加到文本框,但找不到反映相同的代码。现在已添加要添加到文本框的代码。请记住将 TextBox 的 MultiLine 属性更改为 true 以查看多行


推荐阅读