MetaGuru
MetaGuru

Reputation: 43833

Why is my winforms combobox showing the name of the objects rather than the display member that I specify?

Here is the code:

cmbVegas.Items.AddRange((VegasPegasusCourseObject[])convertableCourses.ToArray());
cmbVegas.DisplayMember = "VegasCourseName";
cmbVegas.ValueMember = "CourseMapID";

convertableCourses is a List<VegasPegasusCourseObject>

This is where I am getting the List from:

public List<VegasPegasusCourseObject> GetConvertedCourses()
        {
            using (PanamaDataContext db = new PanamaDataContext())
            {
                IQueryable<VegasPegasusCourseObject> vegasCourses = from cm in db.VegasToPegasusCourseMaps 
                                   join c in db.Courses on cm.VegasCourseID equals c.CourseID
                                   join cp in db.Courses on cm.PegasusCourseID equals cp.CourseID
                                   select new VegasPegasusCourseObject
                                   {
                                       CourseMapID = cm.VPCMapID,
                                       VegasCourseName = c.CourseName,
                                       VegasCourseID = cm.VegasCourseID,
                                       PegasusCourseID = cm.PegasusCourseID,
                                       PegasusCourseName = cp.CourseName
                                   };

                return vegasCourses.ToList();
            }
        }

Here is the obj def:

class VegasPegasusCourseObject
    {
        public int CourseMapID;

        public string VegasCourseName;
        public int VegasCourseID;

        public string PegasusCourseName;
        public int PegasusCourseID;
    }

However when I fire this baby up this is all I am getting:

enter image description here

Upvotes: 4

Views: 5609

Answers (3)

Reddog
Reddog

Reputation: 15579

As per the comments above, the issue is due to the fact that "VegasCourseName" has been written as a field, not a property. Therefore, the ToString implementation has been shown instead.

Use a property instead:

class VegasPegasusCourseObject
{
    public string VegasCourseName { get; set;}
}

Upvotes: 11

Reza ArabQaeni
Reza ArabQaeni

Reputation: 4907

Override ToString() method of VegasPegasusCourseObject class

Upvotes: -1

user957902
user957902

Reputation: 3060

From the docs for DisplayMember:

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.

You do not have a property named "VegasCourseName" in VegasPegasusCourseObject and are getting the ClassName (the default implementation of ToString()) instead.

Upvotes: 1

Related Questions