Add new items to checkboxlist dynamically from a List<> C#

Paradigm picture Paradigm · May 23, 2013 · Viewed 35.9k times · Source

I don't want to add items from the collection HARD-CODED style, I want to populate them from a List<> when a button is pressed.

First i took data from the list like this:

private List<User> _users = new List<User>()

foreach (User user in _users) {
    int index = checkedListBoxDepts.Items.Add(user.UserName);
    upd.checkedListBoxDepts.Items[index] = user;
}

FOR the retrieval of checked items: (I put them in a List of type string):

List<string> Names = new List<string>();

foreach (string s in checkedListBoxDepts.CheckedItems) {
    Names.Add(s);
}

Answer

yclkvnc picture yclkvnc · May 23, 2013

You're getting error because of this line:

upd.checkedListBoxDepts.Items[index] = user;

You're assigning user object to the checkBoxList's items, then trying to retrieve them as strings

This is enough to populate:

private List<User> _users = new List<User>()

foreach (User user in _users) {
    checkedListBoxDepts.Items.Add(user.UserName);
}

You can retrieve checked items as strings afterwards