I have 2 listboxes with SelectionMode = MultiExtended and I just cannot figure out why I get the err

J

Joao

Hi all,

I have 2 listboxes with SelectionMode = MultiExtended and I just cannot
figure out why I get the error below:

System.IndexOutOfRangeException was unhandled
Message="Index was outside the bounds of the array."
Source="System.Windows.Forms"

Listbox Data:
Index String
0 A - Selected
1 B - Not Selected
2 C - Selected

private void button3_Click(object sender, EventArgs e)
{
if (lstBoxAll.SelectedIndex != -1)
{
for (int x = 0; x < lstBoxAll.Items.Count; x++)
{
if (lstBoxAll.GetSelected(x) == true)
{
// when x=2 and lstBoxAll.GetSelected(x) == true, I
still am not able to retrieve the 3rd item from my list
lstBoxSelected.Items.Add(lstBoxAll.SelectedItems[x].ToString());
}
}

//for (int counter = lstBoxAll.SelectedItems.Count - 1;
counter >= 0; counter--)
//{
//
lstBoxAll.Items.Remove(lstBoxAll.SelectedItems[counter]);
//}
}
}

Any ideas?

Thank you
Joao
 
M

Mark Rae

Joao said:
Hi all,

I have 2 listboxes with SelectionMode = MultiExtended and I just cannot
figure out why I get the error below:

System.IndexOutOfRangeException was unhandled
Message="Index was outside the bounds of the array."
Source="System.Windows.Forms"

Listbox Data:
Index String
0 A - Selected
1 B - Not Selected
2 C - Selected

private void button3_Click(object sender, EventArgs e)
{
if (lstBoxAll.SelectedIndex != -1)
{
for (int x = 0; x < lstBoxAll.Items.Count; x++)
{
if (lstBoxAll.GetSelected(x) == true)
{
// when x=2 and lstBoxAll.GetSelected(x) == true, I
still am not able to retrieve the 3rd item from my list

lstBoxSelected.Items.Add(lstBoxAll.SelectedItems[x].ToString());
}
}

//for (int counter = lstBoxAll.SelectedItems.Count - 1;
counter >= 0; counter--)
//{
//
lstBoxAll.Items.Remove(lstBoxAll.SelectedItems[counter]);
//}
}
}

Any ideas?

Yup - you have *three* items in lstBoxAll, but only *two* of them are
selected. Therefore, lstBoxAll.Items.Count = 3, but
lstBoxAll.SelectedItems.Count = 2.

Therefore, lstBoxAll.SelectedItems[2] is outside the bounds of the
SelectedItems collection... :)
 
J

Joao

Hello David and Mark,

I knew what was wrong by looking at the debugger but I could not find the
right object to use.
Now (with your tips) I changed the code to the following:

//add items
for (int x = 0; x < lstBoxAll.SelectedItems.Count; x++)
{
lstBoxSelected.Items.Add(lstBoxAll.SelectedItems[x]);
}
//remove items
for (int counter = lstBoxAll.SelectedItems.Count - 1; counter >= 0;
counter--)
{
lstBoxAll.Items.Remove(lstBoxAll.SelectedItems[counter]);
}

And it worked great! Thank you so much.

Joao
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top