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.
you need to concat the selected items like display +=
or better to use Stringbuilder
display += " Items needed\n-----------\n\n\n" + selectedItems.ToString();
OR you can do as below
if(clb.CheckedItems.Count >0)
display = "Items needed\n-----------\n\n\n" + string.Join(",", clb.CheckedItems.Select( i=>i.ToString()));
else
display = "No items selected";
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.