Article Options
Premium Sponsor
Premium Sponsor

 »  Home  »  .NET Newbie  »  OOP: Create, Collect, Sort, Save and Retrieve Objects  »  A Collection of Players
 »  Home  »  Visual Studio 2005  »  OOP: Create, Collect, Sort, Save and Retrieve Objects  »  A Collection of Players
 »  Home  »  Windows Development  »  Visual Basic 2005  »  OOP: Create, Collect, Sort, Save and Retrieve Objects  »  A Collection of Players
OOP: Create, Collect, Sort, Save and Retrieve Objects
by Ged Mead | Published  03/18/2007 | .NET Newbie Visual Studio 2005 Visual Basic 2005 | Rating:
A Collection of Players

A New Approach

  Prior to the release of VB 2005 creating a collection of objects, such as the Player object, could be quite a fiddly task.  It wasn't rocket science, but did require a little work.  Although you can still use the VB.NET 2002/2003 approach, for the kind of scenario we are working with in this article it's much easier to harness the power of the generic collection to do most of the work for us.

   The great strength of the generic collection is that it automatically gives us a strongly typed collection.   Strongly Typed simply means that it isn't possible to pass an instance of a "wrong" or unacceptable type into a generic collection.   This is very useful because by strongly typing the collection you are effectively locking out any unwanted types that a user might try and add to it.   This in turn means that your application won't crash when - for example - a user took it into his head to do something that tried to add a string to a collection that expected to be asked to store only numbers.   (That's a rather simplistic example, but you get the idea).

    For the purposes of our article, we can create a collection that will only accept Player objects; that is, it is strongly typed to accept those kinds of objects only.

Creating The List

   The code needed is very simple indeed.  We will create a List collection.  This is very similar to the ArrayList, the key difference being its strongly typed nature.   This collection is available from the System.Collections.Generic namespace, so we should first Import this namespace into our form at the very top:

Imports System.Collections.Generic

   I've chosen to create a new form for the code on this page of the article and I named that form Step2.   This is just for demonstration purposes and in your project you can just continue to use the original form.  

   Inside the code for the form (that is, right below the "Public Class Form1"  or "Public Class Step2" line, we can create a new Generic List with:

Dim PlayersList As New List(Of Player)

   i.e. a generic List that will only accept Player instances.

  Here is a revised version of the code that creates a new Player instance.  This version is more robust than our original effort and forces the user to enter at least one letter for the name and a valid numeric value for the score.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click  

' Create a new Player instance:
Dim Player1 As New Player

 If TextBox1.Text.Length > 0 Then
  Player1.Name = TextBox1.Text
  Player1.Score = CInt(TextBox2.Text)
  Windows.Forms.MessageBox.Show("Please enter a Player Name")
  Exit Sub
 End If
Catch NoScore As InvalidCastException
' Optional message:
Windows.Forms.MessageBox.Show("Please enter a valid score")

Catch ex As Exception

End Try

Label3.Text = String.Format("Player Name: {0} {1}Current Score: {2}", Player1.Name, _ ControlChars.CrLf, Player1.Score.ToString)

   Still in the Button Click event, once we have created a new Player instance we will automatically add it to the collection.   This is just a matter of:- 


Player1 = Nothing        ' This instance is finished with.
End Sub

   Try this amended version of the code in your project and create a few Player instances.

   Of course, at this stage you don't have any confirmation that the collection is being built correctly behind the scenes for you.   So let's deal with that now.   Add another button and a ListBox control to the form:


   What we will do is code the second "Show All Players" button to display the contents of the collection in the ListBox.   Here is the code to do that:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

   For Each APlayer As Player In PlayersList
     ListBox1.Items.Add(String.Format("{0}, Current Score: {1}" , APlayer.Name, APlayer.Score.ToString))

End Sub

    Run this code now and add a few new Players, giving them Scores.  Once you have created a few, then click on the new button to see the collection listed for you in the ListBox.   Pretty simple, really.



Sponsored Links