Antoni4 Antoni4 - 1 year ago 67
C# Question

How to give ListBox items meaningful names

I have populated a listBox with items of type:


Now when I run my application the listBox window display items like so:


Instead I want listBox to display each item with string "Region" + item's index.

Like so:





Can someone please explain how I can do this?


This is Windows Forms.

To populate the listBox I use the following code:

listBoxPossibleCandidates.DataSource = possibleCandidates;

And possibleCandidates are populated like this with a loop:

possibleCandidates.Add(Tuple.Create(regionPoints, regionIntensities));

Answer Source

Okay, I found how to do this now. It's done through ListControl.DisplayMember Property.

The reason it was displaying (System.Collection.Generic.List`1[System.Drawing.Point].Systen,Collection...) is because of this:

"If the specified property does not exist on the object or the value of DisplayMember is an empty string (""), the results of the object's ToString method are displayed instead."


Code I used:

class Region
    private int myIndex;
    private List<Point> regionCoordinates;
    private List<int> regionIntensitiesDistinct;

    public Region(List<Point> regionCoordinates, List<int> regionIntensities, int index)
        this.regionCoordinates = regionCoordinates;
        this.regionIntensitiesDistinct = regionIntensities.Distinct().ToList();
        this.myIndex = index;

    public string MyDescription
            return "Region-" + myIndex;

    public List<Point> getRegionCoordinates()
        return regionCoordinates;

    public List<int> getRegionIntensitiesDistinct()
        return regionIntensitiesDistinct;

Now this is how I populate my listBox:

List<Region> possibleCandidates = new List<Region>();

//using loop I add all the regions:
possibleCandidates.Add(new Region(regionPoints, regionIntensities, possibleCandidates.Count));

//after possibleCandidates are populated I pass them to the listBox for display
listBoxPossibleCandidates.DataSource = possibleCandidates;
listBoxPossibleCandidates.DisplayMember = "MyDescription";

The listBox output is now:

* Region-0
* Region-1
* Region-2
* ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download