开发者

Writing content of an array to a textbox using foreach loop C#

开发者 https://www.devze.com 2023-02-14 08:37 出处:网络
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:

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 th开发者_JAVA技巧ere any way this can be done with a textbox and a foreach loop?


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);


You need to append the strings successively.

foreach (int myInt in iData)
        {
            txtListing.Text += myInt.ToString();
        }


The low tech approach:

        foreach (int myInt in iData)
        {
            txtListing.Text = txtListing.Text + "; " + myInt.ToString();
        }


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.


Try:

foreach (int myInt in iData)
{
    txtListing.Text += myInt.ToString();
}

This should append each value to the .Text property, rather than overwrite it.


1) Set

 txtListting.MultiLine = true

2) Change code:

 txtListing.Text += myInt.ToString() + "\n";


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号