I have a string array that I'm storing complete strings into. The array size is 1,000 so that I have plently of space to work with. Storing the strings into the array is working just fine. The part I need help with is removing specific indexes from the array. I have a list box set up that holds the information from the array by string name. I've been trying to use Array[ListBox.SelectedIndex].Replace(Array[ListBox.SelectedIndex], ""); but it keeps throwing an out of bounds exception because the selected index returns a value of -1 for some reason.

// Snippet for storing information into the array.
public void StoreInfo(string Info)
{
MyArray[ListBox.Items.Count] = Info;
ListBox.Items.Add(Info);
}

I've been trying to remove the stored information while removing the list box's selected item. Since that's how it's storing the information anyways. However the selected index variable keeps returning a value of -1 even if the index should be 3.

// Snippet for removing information from the array.
public void Remove()
{
ListBox.Items.Remove(ListBox.SelectedItem);
MyArray[ListBox.SelectedIndex].Replace(MyArray[ListBox.SelectedIndex], "");
DisplayBox.Text.Replace(MyArray[ListBox.SelectedIndex], "");
}
// Snippet for filling the display (rich text box control).
public void ShowAllInfo()
{
for (int i = 0; i < ListBox.Items.Count; i++)
{
DisplayBox.Text = DisplayBox.Text + MyArray[i];
}
}

Please note that the above code snippets are not from the compiler, they are typed in the way I remember typing them. Any help on this subject is greatly appreciated. I'll check back as soon as I can in case any further information is required.

When you remove the item from the ListBox:

ListBox.Items.Remove(ListBox.SelectedItem);

The ListBox.SelectedIndex gets changed to -1, since an item is no longer selected. You could store the SelectedIndex to a local variable before removing any items. You should be careful with this though, you are removing the element from the ListBox, but only changing the element in the array. All elements after the removed index will be off by one.

before you attempt to remove, have a check if there is any items present in the listbox, if yes, only then remove it.

if(ListBox.Items.Count > 0)
{
    ListBox.Items.Remove(ListBox.SelectedItem);
}

This is how we can handle the out of bound exception in your case.

In your Remove(), wat difference does line 4 and 5 make ?

This article has been dead for over six months. Start a new discussion instead.