Reputation:
So, I wanna know how to write the entire content of an array to a textbox by using a foreach loop in C#. My code currently looks like this:
I generate a series of random numbers which are stored in the array:
int[] iData;
Now I want to write the stored data in this array to a textbox by using the foreach loop like this:
foreach (int myInt in iData)
{
txtListing.Text = myInt.ToString();
}
This will only write the last generated number in the array to the textbox, but my question is how do I write all of them to the tekstbox.
I only know, how to do this with a listbox and a forLoop. But is there any way this can be done with a textbox and a foreach loop?
Upvotes: 1
Views: 27182
Reputation: 1
First remove null values of the array using linq:
Array = Array.where(x => !string.isNullOrEmpty(x)).ToArray();
Convert to string:
String result = string.join("",Array);
Write to textbox:
Textbox.text=result.tostring();
Didn´t use foreach but may solve your problem
Upvotes: 0
Reputation: 4433
This is writing the content of each item in turn to the text property, which is leaving the last entry in place as there's no further changes.
You're probably best off using String.Join to concatenate all the values together and write to the Text property.
i.e.
String.Join(", ", iData.Select(x => x.ToString()));
As Fredrik pointed out,
String.Join(", ", iData);
Is neater.
Upvotes: 2
Reputation: 29
1) Set
txtListting.MultiLine = true
2) Change code:
txtListing.Text += myInt.ToString() + "\n";
Upvotes: 0
Reputation: 3854
The low tech approach:
foreach (int myInt in iData)
{
txtListing.Text = txtListing.Text + "; " + myInt.ToString();
}
Upvotes: 2
Reputation: 158309
Try using the AppendText
method instead:
foreach (int myInt in iData)
{
txtListing.AppendText(myInt.ToString());
}
Another option is to join the elements together as a string:
textListing.Text = string.Join(string.Empty, iData);
...or if you want another delimiter:
textListing.Text = string.Join(", ", iData);
Upvotes: 5
Reputation: 218847
Try:
foreach (int myInt in iData)
{
txtListing.Text += myInt.ToString();
}
This should append each value to the .Text
property, rather than overwrite it.
Upvotes: 0
Reputation: 22094
You need to append the strings successively.
foreach (int myInt in iData)
{
txtListing.Text += myInt.ToString();
}
Upvotes: 2