top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

how to create and add items into the ArrayList in csharp

0 votes
150 views
how to create and add items into the ArrayList in csharp
posted May 21, 2016 by Sathaybama

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Create a Windows Form and place the following code in the Form_Load event.

private void Form1_Load(object sender, EventArgs e)
{
    ArrayList arrayList = new ArrayList();
    arrayList.Add("Customer1");
    arrayList.Add("Customer2");
    arrayList.Add("Customer3");
    arrayList.Add("Customer4");
    arrayList.Add("Customer5");

    //Iterating through items - Using foreach loop

    string str = string.Empty;
    foreach (string strName in arrayList)
    {
        str += strName + "\n";
    }
    MessageBox.Show(str);
}

The following statement shows how to create a new instance of an ArrayList class.

ArrayList arrayList = new ArrayList();

Once ArrayList class is instantiated, we can add items to it using the Add method. Click here to know How to add items to the ArrayList using an Add method. When you run this program five customer details are added to the arraylist and displayed.

The below code displays ArrayList data on a new line.

foreach (string strName in arrayList)
    {
        str += strName + "\n";
    }

As we have taken Windows Form as an example, we will see how to display ArrayList data into the textbox controls of a windows form.

ArrayList stores data as object type and so, we need cast it to a string type or by using ToString() method and assign to the Textbox controls as shown below.

txtName.Text  = (string) arrayList[0];
or 
txtName.Text   = arrayList[1].ToString();   
answer May 21, 2016 by Shivaranjini
...