Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding objects to the items collection

How-to

Adding objects to the items collection

by  DotNetDoc  Posted    (Edited  )
To add objects to your listbox's item collection you need to do the following.

'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'% Step 1
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

First Create your object:

Public Class Customer
'Private member variables to hold the data
Private mFirstName As String
Private mLastName As String
Private mAcctNumber As Integer

'Your class constructor
Public Sub New(ByVal fname As String, ByVal lname As String, ByVal acctNum As Integer)
mFirstName = fname
mLastName = lname
mAcctNumber = acctNum

End Sub

'Your public access to your private variables
Public Property FirstName() As String
Get
Return mFirstName
End Get
Set(ByVal Value As String)
mLastName = Value
End Set
End Property

Public Property LastName() As String
Get
Return mLastName
End Get
Set(ByVal Value As String)
mLastName = Value
End Set
End Property
Public Property AcctNumber() As Int32
Get
Return mAcctNumber
End Get
Set(ByVal Value As Int32)
mAcctNumber = Value
End Set
End Property

'Very important. This is what will show in the list box when
'you add the object.
'if you do not override the ToString method
'the name of the object will show in the list box
Public Overrides Function ToString() As String
'This can be whatever you want to show in the listbox
Return LastName & ", " & FirstName
End Function


End Class

'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'% Step 2
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'Create and instance of the object
Dim myCustomer as New Customer("John","Doe",1234)

'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'% Step 3
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'Add object to the listbox\combobox

Listbox1.Items.Add(myCustomer)

'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
'% Step 4
'%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

'To access all the properties of the object

Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim listCustomer As Customer = ComboBox1.SelectedItem

'You can then access its properties
'listCustomer.Firstname
'listCustomer.LastName
'listCustomer.AcctNum
ListBox1.Items.Add(stritem & "has in dex of " & intItem)
End Sub





Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top