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 bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ComboBox: Name/ID values

Status
Not open for further replies.

jalbao

Programmer
Nov 27, 2000
413
US
How do I assign an ID to items that are in a combobox?

I currently run the following loop to fill my combobox with items that are referred to by name (the items were retrieved from a database table):

Do While drFillControllerType.Read() cboControllerType.Items.Add(drFillControllerType.GetValue(0))
Loop

The above loop does only half of what I want it to do - that is, it creates items to be displayed in the combobox (a user friendly name is displayed).

The other half that I would like to do, is associate the names with an ID (the id value will also be derived from the database table). I will use this ID to reference a combobox item elsewhere in my code.

tia

 
I've found that the combo box in Windows forms you have to bind to get the value member. Wherease, the drop down list in web forms behaves more like the combo box in VB 6 , whereupon, you can assign a value to the ID.
 
Create a class....you could even subclass this in a form.
Code:
Public Class ItemData
    Inherits ListViewItem
    Private _Display As String
    Private _key As String
    Public Sub New(ByVal display As String, ByVal key As String)
        MyBase.New()
        _Display = display
        _key = key
        Me.Text = display
    End Sub
    Public Property Display() As String
        Get
            Return _Display
        End Get
        Set(ByVal Value As String)
            _Display = Value
        End Set
    End Property
    Public Property Key() As String
        Get
            Return _key
        End Get
        Set(ByVal Value As String)
            _key = Value
        End Set

    End Property
End Class

'How to populate
Code:
combobox1.items.add(new itemdata(<display>, <key>))

'How to retrieve key
Code:
console.writeline(ctype(combobox1.selecteditem,itemdata).key)

'*Make sure you set the display member to &quot;Text&quot; after the initializecomponents sub is called
Code:
combobox1.DisplayMember = &quot;Text&quot;




Scott
Programmer Analyst
<{{><
 
Like Scott says.

One of the most powerful features of the .NET combo and listboxes is the ability to use an Object as the item. Since all classes ultimately derive from Object -- you can use any class you create as an item in a combo.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top