Antoni4 Antoni4 - 16 days ago 6
C# Question

How to give ListBox items meaningful names

I have populated a listBox with items of type:

Tuple<List<Point>,List<int>>


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

(System.Collection.Generic.List'1[System.Drawing.Point].Systen,Collection...)
(System.Collection.Generic.List'1[System.Drawing.Point].Systen,Collection...)
(System.Collection.Generic.List'1[System.Drawing.Point].Systen,Collection...)


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

Like so:

Region0

Region1

Region2

...

Can someone please explain how I can do this?

Thanks.




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

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."

Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.displaymember(v=vs.110).aspx

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
    {
        get
        {
            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
* ...