To add your own object to a listbox is quite simple, for those who don't know how to do it, I would like to share that short instruction. :)
It's useful for example if we need the possibility to add more or userdefined properties or objects like a Tag, an Image or something else to the
Listbox
Item.
First, we need to create our own object class:
public class ListBoxItem:Object
{
public virtual string Text { get; set; }
public virtual object Tag { get; set; }
public virtual object Object { get; set; }
public virtual string Name { get; set; }
public ListBoxItem()
{
this.Text = string.Empty;
this.Tag = null;
this.Name = string.Empty;
this.Object = null;
}
public ListBoxItem(string Text, string Name, object Tag, object Object)
{
this.Text = Text;
this.Tag = Tag;
this.Name = Name;
this.Object = Object;
}
public ListBoxItem(object Object)
{
this.Text = Object.ToString();
this.Name = Object.ToString();
this.Object = Object;
}
public override string ToString()
{
return this.Text;
}
}
Override the
ToString()
method!
Otherwise the Text will not be displayed in the
Listbox
.
Basically, we only need the userdefined Properties and the
ToString()
Method.
To use the new userdefined object, we add new instances of the user class to the
listbox
, here we add 10 auto-generated entries using a
for
-loop:
for (int i = 0; i < 10; i++)
{
ListBoxItem test = new ListBoxItem();
test.Text = "Objekt " + i;
test.Name = "Ich heiße Objekt " + i;
test.Tag = DateTime.Now;
listBox1.Items.Add(test);
}
To get the
listbox
items back, we convert the
listbox
item to our user class:
ListBoxItem item = (ListBoxItem)listBox1.SelectedItem;
string s = "Text:\t" + item.Text
+ "\nName:\t" + item.Name
+ "\nTag:\t" + item.Tag.ToString();
MessageBox.Show(s, item.ToString());
Another example, used by many books...
Add a car manufacturer, model and color to a
listbox
:
First, we need the Type (Class) "
Car
":
public class Car:Object
{
public virtual string Manufacturer { get; set; }
public virtual string Model { get; set; }
public virtual System.Drawing.Color Color { get; set; }
public Car(string Manufacturer, string Model, System.Drawing.Color Color)
{
this.Manufacturer = Manufacturer;
this.Model = Model;
this.Color = Color;
}
public override string ToString()
{
return string.Format("{0} {1}, {2}",
this.Manufacturer, this.Model, this.Color);
}
}
To add new cars to the
ListBox
:
Car car = new Car("BMW", "530i", System.Drawing.Color.Blue);
listBox1.Items.Add(car);
car = new Car("Audi", "TT", System.Drawing.Color.Black);
listBox1.Items.Add(car);
car = new Car("VW", "Golf", System.Drawing.Color.Red);
listBox1.Items.Add(car);
car = new Car("Mercedes", "230E", System.Drawing.Color.White);
listBox1.Items.Add(car);
To get the object "
Car
" back:
Car car = (Car)listBox1.SelectedItem;
MessageBox.Show(car.ToString(), "Car Info");