在选中列表框中创建一个已选项目的字符串数组

6

如何使用foreach循环(或其他方法)创建一个包含checkedlistbox中选中项的数组?

我不知道列表中有多少项。


System.Windows.Forms.CheckedListBox.CheckedItems? - Kirk Woll
2个回答

13

假设您正在使用3.5或更高版本..

object[] items = lb.CheckedItems.OfType<object>().ToArray();

如果你将特定类型的对象添加到CheckedListBox中,那么你可以用你所使用的类的名称来替换object。


请问你能再帮我一件事吗? 我使用了你写的代码: string[] fonts = fontBox.CheckedItems.OfType<string>().ToArray(); 然后我想把数组中的每个字符串都写在rich text box(名为fontBox)的新行上,所以我尝试了以下两种方法:for (int i = 0; i < fonts.Count(); i++) { fontBox.Text = fonts[i]; }和foreach (string i in fonts) { fontBox.Text = i; }但是它们都没有起作用。 - Gilad Naaman
1
for (int i = 0; i < fonts.Length; i++) - Greg Bogumil
非常感谢,它正在工作=],我还发现了另一个错误,我告诉程序写入已选中项列表框而不是富文本框。 - Gilad Naaman

2

你好,我正在做类似的任务。但是我使用的是ArrayList而不是数组。我使用了以下代码:

ArrayList errorList = new ArrayList();
errorList = chklbErrorlist.CheckedItems.OfType<object>().ToList();

无法隐式将类型 System.Collections.Generic.List<object> 转换为 System.Collections.ArrayList

我先将项添加到数组中,然后再添加到数组列表中,这行得通。如何直接将项添加到数组列表而不是数组中?


1
ArrayList errorList = new ArrayList(chklbErrorlist.CheckedItems.OfType().ToList());错误列表数组 errorList = 新 ArrayList(chklbErrorlist.CheckedItems.OfType().ToList()); - Gilad Naaman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接