我有一个问题,让checkedlistbox显示Windows应用程序的消息框中的所有选择。 我只选择了最后一个显示。 例如,我选择“一,三和五”,只有五个显示。
这是我的代码:
string display = ""; foreach (object selectedItems in clb.CheckedItems) { if (clb.SelectedItems.Count != 0) { display = "Items needed\n-----------\n\n\n" + selectedItems.ToString(); } else { display = "No items selected"; } } MessageBox.Show(display, "Title");任何想法指出我正确的方向来实现这一点是值得赞赏的。
I am having an issue getting the checkedlistbox to display all selections in a message box for a windows application. I am only getting the last one selected to display. For example, I select "one, three, and five", only five displays.
Here is my code:
string display = ""; foreach (object selectedItems in clb.CheckedItems) { if (clb.SelectedItems.Count != 0) { display = "Items needed\n-----------\n\n\n" + selectedItems.ToString(); } else { display = "No items selected"; } } MessageBox.Show(display, "Title");Any ideas to point me in the right direction to accomplish this is appreciated.
最满意答案
您的错误是在选择/检查项目数测试之前开始的循环中。 您的循环继续在每个循环中更改变量显示的值。 最后,变量仅包含最后检查/选择的项目。
所以,我假设您要显示checkitems,而不是selecteditems。 在任何情况下,您都需要遍历集合(在本例中为ChekedItems)并在stringbuilder中累积要显示的项目文本。
string display = ""; // Every item in this collection is an item // with CheckState = Checked or Indeterminate if (clb.CheckedItems.Count != 0) { StringBuilder sb = new StringBuilder(); foreach(string item in clb.CheckedItems) sb.AppendLine(item); display = "Items needed\n-----------\n\n\n" + sb.ToString(); } else { display = "No items checked"; } MessageBox.Show(display, "Title");如果你真的想在选择项上循环,代码是相同的,但只需使用SelectedItems集合
Your error is in the loop that starts before the test of the number of items selected/checked. Your loop continues changing the value of the variable display at each loop. At the end the variable contains only the last item checked/selectd.
So, I assume that you want to display the checkeditems, not the selecteditems. In any case you need to loop over the collection (ChekedItems in this case) and accumulate in a stringbuilder the item texts that you want to display.
string display = ""; // Every item in this collection is an item // with CheckState = Checked or Indeterminate if (clb.CheckedItems.Count != 0) { StringBuilder sb = new StringBuilder(); foreach(string item in clb.CheckedItems) sb.AppendLine(item); display = "Items needed\n-----------\n\n\n" + sb.ToString(); } else { display = "No items checked"; } MessageBox.Show(display, "Title");If you really want to loop on the selecteditems, the code is the same, but just use the SelectedItems collection
更多推荐
发布评论