1

I'm working with C# in a web form. I setup an arraylist. I have a button that add user input in a text box to the arraylist. I'm using the += to print out the arraylist to a label. I'm having trouble just printing out the new entry to the exisiting list. Each time I add, it prints out the whole list again. I understand why it's doing that but just can't wrap my fried brain at the moment how to fix the code so it adds a new entry to the list without repeating the whole list.

protected void Button1_Click(object sender, EventArgs e)
{


    ArrayList itemList = new ArrayList();
    itemList.Add("red");
    itemList.Add("blue");
    itemList.Add("green");
    itemList.Add(TextBox1.Text);

    foreach (object item in itemList)
    {
        Label1.Text += item + "<br />";
    }



}

3 Answers 3

3

Don't use the obsolete ArrayList class. Use a generic version of it, List<T>.

List<string> itemList = new List<string>();
itemList.Add("red");
itemList.Add("blue");
itemList.Add("green");
itemList.Add(textBox1.Text);

Now you can update your label with a single line...

Label1.Text = string.Join("<br />", itemList);

EDIT

Unfortunately, for this example I have to use an arraylist

You can still do it with one line

Label1.Text = string.Join("<br />", itemList.Cast<string>());
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, for this example I have to use an arraylist.
Thank you everyone all the examples work. I having another problem with keeping the previous entry in the arrayList. I think I have to declare a string array and store it in there but not sure, doing the trial and error thing at the moment.
1

Just add Label1.Text = "" before the for loop.

Comments

0

Before you start the loop do this:

Label1.Text = string.Empty;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.