所以,我想知道如何通过在C#中使用foreach循环将数组的整个内容写入文本框.我的代码目前看起来像这样:
我生成了一系列存储在数组中的随机数:
int[] iData;
Run Code Online (Sandbox Code Playgroud)
现在我想通过使用foreach循环将此数组中存储的数据写入文本框:
foreach (int myInt in iData)
{
txtListing.Text = myInt.ToString();
}
Run Code Online (Sandbox Code Playgroud)
这只会将数组中最后生成的数字写入文本框,但我的问题是如何将所有数字写入tekstbox.
我只知道,如何使用列表框和forLoop执行此操作.但有没有办法可以用文本框和foreach循环来完成?
请尝试使用该AppendText方法:
foreach (int myInt in iData)
{
txtListing.AppendText(myInt.ToString());
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是将元素作为字符串连接在一起:
textListing.Text = string.Join(string.Empty, iData);
Run Code Online (Sandbox Code Playgroud)
...或者如果你想要另一个分隔符:
textListing.Text = string.Join(", ", iData);
Run Code Online (Sandbox Code Playgroud)