Creating Custom Collections and Binding Them
I thought this was too cool so I decided to post an example on it.
First Create A Class
We need to create a class the items of which we will add to our custom collection. This one’s pretty simple, it’s a car:
‘ Quick class to give us some properties
Public Class CarItem
Public _Make As String
Public _Model As String
‘you have to implement the properties to be able to bind it later on
‘ (i.e. declaring the variables as Public won’t work)
Public Property Make() As String
Get
Return _Make
End Get
Set(ByVal Value As String)
_Make = Value
End Set
End Property
Public Property Model() As String
Get
Return _Model
End Get
Set(ByVal Value As String)
_Model = Value
End Set
End Property
End Class
Create The Custom Collection
The important parts to note are the first line where we inherit from System.Collections.CollectionBase. This provides all the basic functionality of the collection to us.
The next thing we do is to re-implement the Add and Item properties. This is what makes it so cool. Later on when you access these properties the intellisense knows that your adding a “CarItem” object and you have all the properties of the “CarItem” available.
The Microsoft article made the Item property ReadOnly. I’m not sure why, I decided to implement the Item property just like the Base object’s Item Property (allowing Get and Set).
‘This is the custom collection that we can populate and do things like bind to .NET controls
Public Class Cars
Inherits System.Collections.CollectionBase
‘Re-implement the Add method, but type it to our object
Public Sub Add(ByVal Car As CarItem)
list.Add(Car)
End Sub
‘Reimplement the Item property but type it
Public Property Item(ByVal index As Integer) As CarItem
Get
Return CType(list.Item(index), CarItem)
End Get
Set(ByVal Value As CarItem)
list.Item(index) = Value
End Set
End Property
End Class
Using The New Collection
Now that we’ve created our new collection we can use it. The code below shows an example of how you might bind the collection to a datagrid. Obviously you’d probably be adding the data from a database and not manually, but this is good enough for example. The last line also shows how you can use the item property to inspect the items within the collection.
Dim MyCarCollection As New Cars
‘This would be better done through a database 🙂
Dim Car1 As New CarItem
With Car1
._Make = “Ford”
._Model = “Ranger”
End With
MyCarCollection.Add(Car1)
Dim Car2 As New CarItem
With Car2
._Make = “Jeep”
._Model = “Wrangler”
End With
MyCarCollection.Add(Car2)
‘Assign our custom car collection to the cars datagrid and bind it
dgCars.DataSource = MyCarCollection
dgCars.DataBind()
Response.Write(MyCarCollection.Item(0).Make)
Here’s an Example of The DataGrid After Being Bound
Pretty cool eh?
Here’s the original Microsoft Article which I basically re-implemented here 😛