ListBox question

Hi to all!

I have a question about ListBox control. I would like to add some items

on a ListBox which are objets (for example type of MyOwnObject) and are

not strings! When I add my objects to the ListBox

(myListBox.Items.Add(myOwnObject)) of corse nothing displays on the

ListBox. I would actually like to display only some properties of my

objects (for example myOwnObject.Name + myOwnObject.Version +

myOwnObject.LastUpdated). I don't know how to do it. The fact is I want

to have the whole objects in myListBox.Items because of the binding

(raising events) not only strings.

Thanx for any advice,

Ziga

[628 byte] By [fddsfsdf] at [2007-12-23]
# 1

Hi fddsfsdf,

A common question, the ListBox ObjectCollection is confusing.

When using objects as Items in a ListBox the ToString() method of your object, myOwnObject.ToString(), is used to display a text in the ListBox. One way to solve your problem is to override the ToString method of your myOwnObject and have it return whatever you want to display.
Note that, contrary to what you would expect, this solution doesn't work for Controls. It only works for Objects.

A more general solution is to use a wrapper class. Example:
class MyWrapper
{
public MyWrapper(string text, object object_)
{
this.text = text;
this.object_ = object_;
}

private string text;
public string Text
{
get { return text; }
set { text = value; }
}

private object object_;

public object Object
{
get { return object_; }
set { object_ = value; }
}

public override string ToString()
{
if (text != null)
return text;
else
if (object_ != null)
return object_.ToString();
else
return
"";
}
}

Use it like this:
listBox1.Items.Add(new MyWrapper("sometext", new Class1()));

Note that your supplied text is shown unless it is set to null. In that case you get the ToString()..

Regards, Tonn

tonn at 2007-8-30 > top of Msdn Tech,Windows Forms,Windows Forms General...
# 2
Tonn!

Thanks a lot! That's exactly what I needed.

fddsfsdf at 2007-8-30 > top of Msdn Tech,Windows Forms,Windows Forms General...
# 3

hi,

mark the answer as reply plz

Egyptian at 2007-8-30 > top of Msdn Tech,Windows Forms,Windows Forms General...