How to display objects in a ListBox?

I

Ikke

Hi everyone,

I've created an ArrayList in which there are Objects of type 'Item'. Item
is a simple class which holds a sequence and a link, of which the link
should be displayed in the ListBox.

I've overwritten the property ToString to return the link, yet the ListBox
only shows the name of the item (Test.Item) instead of the link.

What should I do to get the link instead of the class name of Item?

Thanks!

Ikke
 
M

Morten Wennevik [C# MVP]

Hi Ikke (meaning 'Not' in Norwegian ;) ),

Did you override ToString on the Item class?
Another solution is to specify which property should be used setting thename of the property in the ListBox' DisplayMember property.

private void Form1_Load(object sender, EventArgs e)
{
ArrayList list = new ArrayList();
list.Add(new Item());
list.Add(new Item());
list.Add(new Item());

listBox1.DataSource = list;
// listBox1.DisplayMember = "Link";
}

public class Item
{
string link = "http://w3.org";

public string Link
{
get { return link; }
}

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

This will work using overridden ToString, or if you uncomment the line, using a property and displaymember
 
I

Ikke

Hi Ikke (meaning 'Not' in Norwegian ;) ),

Thanks, I did not know that... In Dutch, it means "me".
Did you override ToString on the Item class?

I tried to do that, but I got an error. After seeing and trying your
example, I realise now that I tried to treat ToString as a property. Of
course, that did not work.

Coming from a Java background, these properties are a bit strange to me,
I'm used to all the getter & setter methods :)
Another solution is to specify which property should be used setting
the name of the property in the ListBox' DisplayMember property.

Thanks - I found this out after taking a long hard look at the methods &
properties of ListBox.

This will work using overridden ToString, or if you uncomment the
line, using a property and displaymember

Thanks again for the help, Morten!

Best regards,

Ikke
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top