'Tag' object for each item in ComboBox

  • Thread starter Thread starter Guest
  • Start date Start date
khalprin,

Item in the cobobox can be any object you want.What cobobox shows is what
ToString returns. Since it can be any object of any type you can assign
whatever 'Tag' you want.
 
In other words, there is no longer any need for a Tag property on each item.
The Tag is traditionally used to hold additonal relevant data for an
item. However, since the .NET list controls all hold a collection of
"objects", and not just "strings", each item can already hold all the
data it needs.

Think of it this way... if you just want to hold strings, with some
associated random data, create a class like this:
class ComboBoxItem {
string _Contents;
public string Contents {
get { return _Contents; }
set { _Contents = value; }
}
object _Tag;
public object Tag {
get { return _Tag; }
set {_Tag = value; }
}
public ComboBoxItem(string contents, object tag)
{
this._Contents = contents;
this._Tag = tag;
}

public override string ToString(){ return _Contents; }
}

Then, when you want to add your strings to the comboxbox, instead of
adding them directly like this:
comboBox1.Items.Add("My first item");

Do it like this:
// the second parameter can be anything you want,
// here I'm using the integer '1' as my tag data
comboBox1.Items.Add(new ComboBoxItem("My First item", 1));

If you already have a custom class, you don't need the ComboBoxItem
class - just make sure its ToString() method returns the string you want
to appear in the combobox, as Stoicho alluded to.

Hope that helps.

Joshua Flanagan
http://flimflan.com/blog
 
* "=?Utf-8?B?a2hhbHByaW4=?= said:
Can a Tag object be associated with each item in a ComboBox? If so, how?

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

' Test.
MessageBox.Show(DirectCast(Me.ComboBox1.Items.Item(0), Person).ToString())
..
..
..
Public Class Person
Private m_Name As String
Private m_Age As Integer

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

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

Public Overrides Function ToString() As String
Return Me.Name & " (" & Me.Age.ToString() & ")"
End Function
End Class
///

Alternatively, you can use a bound combobox:

\\\
With Me.ListBox1
.DataSource = Database.FindPeople(...)
.DisplayMember = "Name"
.ValueMember = "Age"
End With
///
 
Back
Top