Search code examples
c#.netwinformsdatasourcecheckedlistbox

CheckedListBox datasource not displaying correctly


I have the following code

clbCodes.DisplayMember = "Name";
clbCodes.ValueMember = "Id";

checkboxItemList = new List<CheckBoxItem>();
foreach (var uagCode in codes)
{
    var checkboxItem = new CheckBoxItem
        {
            Id = uagCode.Code,
            Name = uagCode.UAGLabel
        };
    checkboxItemList.Add(checkboxItem);
}

clbCodes.DataSource = checkboxItemList;

public class CheckBoxItem
{
    public string Name { get; set; }
    public string Id { get; set; }
}

However, when I run this, instead of seeing the "Name" of my item, e.g.,

"Card"
"Toy"
"Table"

I see

WindowsApplication1.CheckBoxItem 
WindowsApplication1.CheckBoxItem 
WindowsApplication1.CheckBoxItem 

populated in my listbox

What did I do wrong?


Solution

  • Since it appears that you are adding to the CheckListBox a collection of custom objects, you should have as part of that class an override of ToString() that can return the Name that you are wanting to display.

    public override String ToString()
    {
        return this.Name;
    }