Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 376
Paradigm Avatar asked Feb 01 '26 20:02

Paradigm


1 Answers

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

like image 85
yclkvnc Avatar answered Feb 03 '26 10:02

yclkvnc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!