c# - 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]);
}
解决方案
问题在于以下行。
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 以查看多行
推荐阅读
- c# - 为什么我不能在需要相同上下文的控制器中注入需要 httpclient 和 EF 上下文的服务
- sql - 如何按特定顺序分组?
- excel - 从特定工作表中删除特定列会导致“未定义子或函数”编译错误
- java - 每当在任何其他服务中自动装配时,如何使 POJO 在 setter 中返回修改后的值?
- python - KERAS: AttributeError: 'BatchDataset' object has no attribute 'ndim' ,Tensorflow 图像分割演示不适用于我的 anaconda
- java - 服务在 android 8 (oreo) 下意外停止
- python - Matplotlib Axes3D 比率 Savefig
- angular - 使用 Angular 6 和 rdflib 0.19.0 找不到模块“算法/RSASSA-PKCS1-v1_5”
- javascript - Gremlin,javascript:从哪里导入函数“valueMap()”?
- python - 使用python将文件从文件夹导入数组