How can I dynamically populate a CheckedListBox?
Asked Answered
B

2

6

I want to populate a CheckedListBox based on the items passed into a form's constructor (in this case, a List<int>).

My skeleton code for this is:

foreach (int platypus in listPlatypi)
{
    userFriendlyPlatypusName = ExpandFromPlatypusID(platypus);
    // I want to store a verbose string in an Item of the CheckedListBox, something like:
    // Item item = new Item(userFriendlyPlatypusName); // what data type should "Item" be?
     CheckedListBox1.Add(item);
}
Bontebok answered 19/7, 2012 at 15:55 Comment(0)
C
9

Were you looking for checkedListBox1.Items.Add(userFriendlyPlatypusName); ?

Casual answered 19/7, 2012 at 16:41 Comment(2)
oh, boy - why that wasn't obvious to me yesterday is now mind-boggling and embarrassing.Bontebok
Don't be embarrassed: I made the EXACT same just 5 minutes ago. Thanks @ keyr for the answer and you for the question.Chicken
K
5

The answer depends on what you are doing outside of the skeleton code listed. What matters is what information your code needs when acting on the list items later.

CheckedListBox works just like ListBox. The text displayed is the result of each item's .ToString().

If strings work, then add the display name text.

If you need more information stored per Item, add a ToString() override to your class and .Add() the full item.

If that's not an option, create a small display wrapper:

public class PlatypusDisplayWrapper {
   public Platypus {get; set;}
   public override string ToString() { 
       return this.Platypus.Name;
   }
}
Krems answered 19/7, 2012 at 16:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.