Drop Down

  • Thread starter Thread starter Sebastian Santacroce
  • Start date Start date
S

Sebastian Santacroce

Is there an easy way to store a value with an ID in a drop
down list. ie making it an array and showing only the
value and not an ID. I believe this was possible in VB 6.

So that when they select a value I can get its
corresponding ID that is stored in a database for example.

If not what would be the easiest way to do this?

Thank you.

Sebastian
 
Hi Sebastian,

First off, I'm assuming that you're talking about WinForms, not WebForms.

The ListBox has an Item collection which accepts any sort of object. (They
needn't even be the same sort within a given list).

To display the list the ListBox calls the ToString() function of each
item. In the case of strings and numbers this will give the string or number.
In the case of objects it will give whatever has been coded. If there is no
ToString() then the default is that of Object which returns the object's type
name.

So if you define an object (class or structure, class perhaps better) and
override the ToString() then you can have your list display what you want and
have access to any associated information.

'This is not the best way to design a class, but it shows the principle.
Public Class NameAndIdForListBox
Public Name As String
Public Id As Integer
Public Sub New (ThisName As String, ThisId As Integer)
Name = ThisName
Id = ThisId
End Sub
Public Overrides Function ToString As String
Return Name
End Function
End Class

ListBox1.Items.Add (New NameAndIdForListBox ("Foo", 23))
ListBox1.Items.Add (New NameAndIdForListBox ("Bar", 77))
ListBox1.Items.Add ("And now for something completely different.")

Regards,
Fergus
 
Hello,

Sebastian Santacroce said:
Is there an easy way to store a value with an ID in a drop
down list. ie making it an array and showing only the
value and not an ID. I believe this was possible in VB 6.

So that when they select a value I can get its
corresponding ID that is stored in a database for example.

If not what would be the easiest way to do this?

\\\
Dim p As New Person()
p.Name = "Pink Panther"
p.Age = 22

Me.ComboBox1.Items.Add(p)

MessageBox.Show( _
DirectCast(Me.ComboBox1.Items.Item(0), Person).ToString() _
)
..
..
..
Public Class Person
Private m_strName As Object
Private m_intAge As Integer

Public Property Name() As String
Get
Return m_strName
End Get
Set(ByVal Value As String)
m_strName = Value
End Set
End Property

Public Property Age() As Integer
Get
Return m_intAge
End Get
Set(ByVal Value As Integer)
m_intAge = Value
End Set
End Property

Public Overrides Function ToString() As String
Return m_strName & " (" & m_intAge.ToString() & ")"
End Function
End Class
///
 
Back
Top