Reputation: 127
I wrote a code that transfers selected items in the first checkedlistbox into another checkedlistbox.This part of the code works(however i still have to find a way so the same selected items dont get written over and over again).My second goal is to remove the selected items from the first checkedlistbox. The error that I'm getting is the array is out of bounds.
private void button_ekle_Click(object sender, EventArgs e)
{
int i = 0;
int k = 0;
i = clb_input.Items.Count;
//the number of items in the first checkedlistbox
for (k = 0; k <i; k++)
{
if (clb_input.GetItemChecked(k) == true)
{
//clb_output is the second checkedlistbox
clb_output.Items.Add(clb_input.Items[k]);
clb_input.Items.Remove(clb_input.CheckedItems[k]);
i--;
}
else { }
}
}
Upvotes: 1
Views: 147
Reputation: 216358
Your problem is caused by the use of indexer k on the CheckedItems collection.
The CheckedItems collection could have lesser elements than the count of the Items collection so the indexer could have a value that is not included in the CheckedItems collection.
However when you need this kind of code it is common to invert the loop.
Starting from the end and walking toward the begin
private void button_ekle_Click(object sender, EventArgs e)
{
for (int k = clb_input.Items.Count - 1; k >= 0; k--)
{
if (clb_input.GetItemChecked(k) == true)
{
clb_output.Items.Add(clb_input.Items[k]);
// Remove from the Items collection, not from the CheckedItems collection
clb_input.Items.RemoveAt(k);
}
else { }
}
}
You should also remember that when you wish to loop over a collection with a traditional for loop, your limiting index value is the count of items less 1 because every collection in NET start at index 0. So, if you have a collection with 10 items the valid indexes are from 0 to 9.
Upvotes: 4