wael razouk wael razouk - 3 months ago 21
C# Question

c# how to add an object to my listbox but display a string

I know my question might be already asked, but no given answer worked for me.
I have a class named "Item" and I want to add Items to my listbox, but with strings displayed like myItem.name.
I tried the suggested solution at this question
c# add object to listbox and show string of object in it
which is:

listBox.DisplayMember = myItem.name;
listBox.ValueMember = myItem.id;
listBox.Items.Add(myItem);


but it keeps displaying namespace.Item not the item's name.

Also I added MouseEventHandler on MouseClick, how to get selected item in listBox_MouseClick function
Any idea please!!!

my class code:

class Item
{
public string name;
public Item parent;
public List<Item> sons = new List<Item>();
public int depth = 0;
public int id = 0;

private static int nextID = 0;

public Item()
{

}

public Item(string Path)
{
this.name = Path;
this.parent = null;
this.sons.Clear();
this.depth = 0;
this.id = nextID;
nextID++;
}

public Item(Item Parent, string Path, int Depth)
{
this.parent = Parent;
this.name = Path;
this.sons.Clear();
this.depth = Depth;
this.id = nextID;
nextID++;
}

public bool isRoot()
{
bool root = false;
if (this.parent == null)
root = true;
return root;
}

public bool isFile()
{
bool file = false;
if (this.sons.Count == 0)
file = true;
return file;
}
}

Answer

You have to override the ToString method in your Item class to make the ListBox display what you want. Because it uses the default ToString method of the class which displays what you see.

try this:

public override string ToString()
{
    // choose any format that suits you and display what you like
    return String.Format("Name: {0}", this.name);
} 

and use your regular approach

or use binding to get your items into the ListBox. You would need a List with your Items

List<Item> itemList = new List<Item>();
// populate it with you items and in the end
// bind it to the data source
this.listBox1.DataSource = itemList;

in any case you have to override the ToString method.

If you want to change your itemList don't forget to refresh the ListBox:

listBox1.Refresh();
listBox1.Update(); 
Comments