从 List<> C# 动态添加新项目到复选框列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16711921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:44:17  来源:igfitidea点击:

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

c#dynamically-generatedcheckedlistbox

提问by Paradigm

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.

我不想从集合 HARD-CODED 样式中添加项目,我想在按下按钮时从 List<> 填充它们。

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);
}

回答by yclkvnc

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

您将用户对象分配给 checkBoxList 的项目,然后尝试将它们作为字符串检索

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

之后您可以将选中的项目作为字符串检索