Article Options
Recently Viewed
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

Try
 If TextBox1.Text.Length > 0 Then
  Player1.Name = TextBox1.Text
  Player1.Score = CInt(TextBox2.Text)
 Else
  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:- 

PlayersList.Add(Player1)

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

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

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.

  

 

Comments    Submit Comment

Comment #1  (Posted by Adam D. on 03/22/2007)
Rating
Excellent article Ged, much appreciated.
 
Comment #2  (Posted by an unknown user on 03/23/2007)
Rating
Cool!
 
Comment #3  (Posted by an unknown user on 03/28/2007)
Rating
Well done helped me get a grasp of VB.NET 2006
 
Comment #4  (Posted by an unknown user on 05/09/2007)
Rating
The explanations are adequate and the code is very clearly exposed. The code works neatly.
 
Comment #5  (Posted by mike holman on 05/09/2007)
Rating
this has proven to be a WONDERFUL application to learn from. very well explained, and i've been customizing this application to learn even more.

picking apart the code, line by line, has taught me a great deal. it's not too complex of an application, nor is it too simple. being an absolute beginner in vb.net, this site is a godsend, and it's great to have experienced programmers take the time to create tutorials like this.

thanks!!!!!
 
Comment #6  (Posted by an unknown user on 05/25/2007)
Rating
its good
 
Comment #7  (Posted by an unknown user on 06/04/2007)
Rating
Another excellent article from Ged.
He just gets the things across very much entertaining.
This guy is good !
Wonder if he is up to write a book.
 
Comment #8  (Posted by an unknown user on 07/08/2007)
Rating
Excellent. I really learned a lot from this. Keep up the good work
 
Comment #9  (Posted by an unknown user on 07/08/2007)
Rating
Excellent. I really learned a lot from this. Keep up the good work
 
Comment #10  (Posted by an unknown user on 08/10/2007)
Rating
Great, easy and comprehensive, summarization of important techniques.

Thanks a lot!
 
Comment #11  (Posted by an unknown user on 08/17/2007)
Rating
Not counting 'Hello, World!' this was my first experience with VB anything. The tutorial was well thought out and implemented. The variety topics was enough to keep my interest with out becoming over whelming.

Thank a Bazillion
 
Comment #12  (Posted by an unknown user on 08/20/2007)
Rating
Been Programming for a few years now and this is the best artical I have ran accross. I wasnt sure how they used the new generic class type for VB2005. Nice Work.
 
Comment #13  (Posted by an unknown user on 08/27/2007)
Rating
Thank you!

I have been playing with vb.net for a while and have tried following several tutorials trying to make a high score board for tetris as a learning project. I got frustrated, however, as they were all explained poorly and I struggled to follow them.

This article is very clear and well explained and I actually understand writing to and reading from binary files now. Thank you very much.
 
Comment #14  (Posted by an unknown user on 11/08/2007)
Rating
was a fun guide to recreate thnx for your time and effort Ged.
 
Comment #15  (Posted by an unknown user on 11/08/2007)
Rating
was a fun guide to recreate thnx for your time and effort Ged.
 
Comment #16  (Posted by an unknown user on 12/19/2007)
Rating
it's good pice of work about write file and read file again excellent

thanks for this article

 
Comment #17  (Posted by an unknown user on 01/23/2008)
Rating
Great stuff. Easy to understand and use even for a meathead like me. It would be wonderfull if you expanded this article to include more functions like edit, remove and delete all. Many thanks

Bob
 
Comment #18  (Posted by an unknown user on 01/25/2008)
Rating
Easy to understand.
 
Comment #19  (Posted by Clint on 04/17/2008)
Rating
Please excuse me. I've very new at .NET. When I create my form and enter the code "Dim Player1 As New Player(TextBox1.Text, CInt(TextBox2.Text))
Label3.Text = String.Format("Player Name: {0} {1}Current Score: {2}", Player1.Name,
ControlChars.CrLf, Player1.Score.ToString)" as the click event I get an error saying that label3 is not declared. How do I fix this?
 
Comment #20  (Posted by an unknown user on 06/02/2008)
Rating
it was really easy to understand and well set out
thanx
 
Comment #21  (Posted by an unknown user on 05/08/2009)
Rating
Very well explained throughout
 
Comment #22  (Posted by an unknown user on 08/03/2009)
Rating
Easy to understand!
Thanks Ged!
 
Sponsored Links