listbox additem

vishalmarya

New member
Joined
Aug 6, 2006
Messages
4
Location
New Delhi, India
Programming Experience
5-10
i want to add items in a listbox along with its corresponding id.my code :
VB.NET:
Private Sub Form1_Load(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles MyBase.Load
    Dim obj As class1obj = New class1
    obj.name = "xyz"
    obj.id = 1
    ListBox1.Items.Add(obj)
    obj = New class1
    obj.name = "pqr"
    obj.id = 2
    ListBox1.Items.Add(obj)
End Sub

Private Class class1
    Public name As String
    Public id As Integer
End Class
result shown on the form is :windowsapplication1.form1+class1windowsapplication1.form1+class1Any suggestions.
 
Last edited by a moderator:
Hi vishalmarya

There are two things wrong with your code:
1. You've added two objects to the list box but you haven't told the list box which property of the object to display and, optionally, which property to use as a value. By default the list box will perform a ToString() on your objects and display the return value. Add the following code before you add the objects:

VB.NET:
ListBox1.DisplayMember = "name"
ListBox1.ValueMember = "id"

This tells the list box to display the 'name' property and use the 'id' property as a value.

2. The second problem is that 'id' and 'name' must be properties, therefore use the following code for class1:

VB.NET:
Private Class class1
Private _name As String
Public Property name() As String
Get
Return _name
End Get
Set(ByVal Value As String)
_name = Value
End Set
End Property
 
Private _id As Integer
Public Property id() As Integer
Get
Return _id
End Get
Set(ByVal Value As Integer)
_id = Value
End Set
End Property
End Class
Hope this helps.
 
Last edited by a moderator:
Back
Top