Search code examples
c#winformscheckedlistbox

Returns System.Object


I'm passing a List<object> to a method that populates a checkedListBox. My understanding is Object.ToString() associates the object with the checkedListBox item and displays readable string. Object.Name accomplishes this, but then the data isn't associated with the item. How do I access the ValueMember property of the checkListBox item?

public void CategoryListBox(List<Category> categoryList)
{
    checkedListBox1.Items.Clear();

    foreach (Category category in categoryList)
    {     
        checkedListBox1.Items.Add(category);
    } 
}

Solution

  • ValueMember of CheckBoxList

    From the answer of Mr. codingbiz I did some quick research for this control checkListBox about ValueMember Property, so obviously from Intellisense we can't navigate this .DisplayMember and .ValueMember for checkListBox, so I figured it out that this Property is already included in checkListBox but not showing in it. For more details

    To List all the name

    By using Linq we can achieve this.

      public class Category
      {
        public int Id { get; set; }
        public string CategoryName { get; set; }
      }
    
    
      List<Category> category = new List<Category>();
      category.Add(new Category { Id = 1, CategoryName = "test"  });
      category.Add(new Category { Id = 2, CategoryName = "let" });
      category.Add(new Category { Id = 3, CategoryName = "go" });
      checkedListBox1.DataSource = category;
      checkedListBox1.DisplayMember = "CategoryName";
      //checkedListBox1.ValueMember = "Id"; 
      //checkedListBox1.Items.AddRange(category.Select(c => c.CategoryName).ToArray());
    

    I hope you can get some idea from this answer.