«^»
8. Using an ArrayList to record the events

As well as confirming what has happened in a Label of the Form, perhaps we would like to record what has happened in a data structure. We could use an ArrayList for this.

We will need to refer to the ArrayList from several methods of the Form1 class and so an ArrayList variable (called iArrayList) can be declared as a Private variable of the class:

0225: Public Class Form1
0226:     Inherits System.Windows.Forms.Form
0227: 
0228:     Private iArrayList As ArrayList
0229: #Region " Windows Form Designer generated code "

An ArrayList object has to be created and assigned to the iArrayList variable. As we want this to be done just once, an obvious place for doing this is in Form1's constructor:

0231:     Public Sub New()
0232:         MyBase.New()
0233: 
0234:         'This call is required by the Windows Form Designer.
0235:         InitializeComponent()
0236: 
0237:         'Add any initialization after the InitializeComponent() call
0238:         iArrayList = New ArrayList
0239:     End Sub

And then the code of each method handling button clicks can be altered:

0335:     Private Sub Button1_Click(ByVal sender As System.Object, _
0336:             ByVal e As System.EventArgs) Handles Button1.Click
0337:         iArrayList.Add(TextBox1.Text)
0338:         Label1.Text = TextBox1.Text + " has arrived"
0339:     End Sub
0340: 
0341:     Private Sub Button2_Click(ByVal sender As System.Object, _
0342:             ByVal e As System.EventArgs) Handles Button2.Click
0343:         iArrayList.Remove(TextBox1.Text)
0344:         Label1.Text = TextBox1.Text + " has departed"
0345:     End Sub
0346: 
0347:     Private Sub Button3_Click(ByVal sender As System.Object, _
0348:             ByVal e As System.EventArgs) Handles Button3.Click
0349:         TextBox2.Clear()
0350:         For Each tString As String In iArrayList
0351:             TextBox2.AppendText(tString & vbCrLf)
0352:         Next
0353:     End Sub
0354: End Class