How to Display the Contents of an Array List in a Text Box in C#

By Jaime Avelar

The ability to display the contents from an "ArrayList" through controls can make your application more user-friendly and more dynamic. In a Microsoft Visual C# program, it's common to display contents from an "ArrayList" through a text box control. An "ArrayList" is used instead of a normal Integer or String array in cases when you don't know how many indexes you're going to need. With an "ArrayList" the size is dynamically increased as required.

Things You'll Need

  • Microsoft Visual C# Express

Step 1

Launch Microsoft Visual C# Express and select "New Project..." from the left pane of your computer screen. Click "Visual C#" below "Installed Templates" and double-click "Windows Forms Application."

Step 2

Click the "Toolbox" pane and double-click "TextBox" to add a new text box control. Double-click "Button" to add a new button to your Form.

Step 3

Double-click "button1" to open the C# code module. Type the following code in the first line of the code module to declare the "Systems.Collections" namespace:using System.Collections;

Step 4

Type the following code inside the "button1_Click" procedure to create a "String" variable and your array list: string ArrayData = string.Empty; ArrayList listData = new ArrayList();

Step 5

Type the following to add five text items to the array list: listData.Add("item1"); listData.Add("item2"); listData.Add("item3"); listData.Add("item4"); listData.Add("item5");

Step 6

Type the following to read the contents of the array list and save them to the "String" variable:foreach (string textItem in listData) { ArrayData = ArrayData + ", " + textItem; }

Step 7

Type the following to display the contents of the array list in the text box:this.textBox1.Text = ArrayData;

Step 8

Press "F5" to run your program and click "button1" to display the contents in the text box.

References & Resources