-1

So I have three listboxes, and the goal is once a user clicks on an item in one listbox and hits the delete button on the form it deletes that item, and then the items in the other 2 listboxes at the same level.

So deleting the fifth element of listbox 1 deletes the fifth element of listbox 2 and 3.

private void btnDelete_Click(object sender, EventArgs e)
{
    lstBox1.Items.Remove(lstBox1.SelectedItem);
    lstBox2.Items.Remove(lstBox2.SelectedItem);
    lstBox3.Items.Remove(lstBox3.SelectedItem);
}

So with what I have so far it will delete a single item from a listbox, but obviously there's nothing to deal with deleting the items from the other listboxes.

Any ideas?

Grigoris Loukidis
  • 383
  • 2
  • 7
  • 23

2 Answers2

2

If by same level, you mean the index, then this can easily be done like this:

private void btnDelete_Click(object sender, EventArgs e)
{
    var itemIndex = listBox1.SelectedIndex;
    listBox1.Items.RemoveAt(itemIndex);
    listBox2.Items.RemoveAt(itemIndex);
    listBox3.Items.RemoveAt(itemIndex);
}
ThePerplexedOne
  • 2,920
  • 15
  • 30
0

You can use SelectedIndex together with RemoveAt method:

if (listBox1.SelectedIndex >= 0)
{
    listBox3.Items.RemoveAt(listBox1.SelectedIndex);
    listBox2.Items.RemoveAt(listBox1.SelectedIndex);
    listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}

you must remove lastly from listBox1 because you are reading the index from that listbox unless you copy the value into a new variable, as shown in example above.

Bizhan
  • 16,157
  • 9
  • 63
  • 101
M. Bauer
  • 199
  • 2
  • 9
  • `you must remove lastly from listBox1 because you are reading the index from that listbox.` unless you copy the value into a new variable, as shown in my example. – ThePerplexedOne Dec 05 '19 at 15:18