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

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.

...
Loop through ArrayList and display items in a control.

Step

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

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

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:

Step

using System.Collections;

Step

Type the following code inside the “button1_Click” procedure to create a “String” variable and your array list:

Step

Type the following to add five text items to the array list:

Step

Type the following to read the contents of the array list and save them to the “String” variable:

Step

foreach (string textItem in listData) { ArrayData = ArrayData + ", " + textItem; }

Step

Type the following to display the contents of the array list in the text box:

Step

this.textBox1.Text = ArrayData;

Step

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