views:

147

answers:

2

I'm having an issue displaying an object in a checked list box in C#. I can add object fine, but when the object is displayed to the user, to the program outputs the checkbox selection as Salesform.order instead of invoking the tostring method in the order class like I want. This results in multiple orders displaying as the same thing: "Salesform.order".

orderCheckList.Items.Add(orderUp);

(here, orderUp is an order with fields such as name of customer and so on)

Can anyone help? I know there is a simple solution that I'm overlooking.

+4  A: 

.ToString() is getting called on each item you add to the list box. Override it to solve this issue.

Ragepotato
+5  A: 

Set the DisplayMember of the CheckedListBox to the property you want displayed. For instance:

orderCheckList.DisplayMember = "Title";
// Now orderUp.Title will be displayed

(Overriding ToString() will work as well, as suggested by Ragepotato, but using DisplayMember is more flexible as it means you can use the same datatype in various different contexts.)

Sample code:

using System.Windows.Forms;

class Test
{
    static void Main()
    {
        Form f = new Form
        {
            Controls =
            {
                new CheckedListBox
                {
                    Items = 
                    {
                        new { FirstName = "Jon", LastName = "Skeet" },
                        new { FirstName = "Holly", LastName = "Skeet" }
                    },
                    DisplayMember = "FirstName"
                }
            }
        };
        Application.Run(f);
    }
}
Jon Skeet