Frage

I have 2 listboxes on a windows form and 2 button at the middle of those boxes. one shows right other shows left. what I want to do is when I select some items lets say on listbox1 and click on the right showing button, I want to copy the items I selected on listbox1 to listbox 2 at the same indexes where I selected them on 1. I can do this, however I can't copy the empty rows. This is how my listboxes looks like(i added the numbers just to track the lines easily here).

    ListBox1                Listbox2

1.  u                       a
2.
3.  l                       c
4.                          b
5.  m                       e
6.                          f
7.  n      >>(right button)          
8.                          c
9.  z      <<(left button)  t
10.                         q
11. s                         
12.                        
13. g                       b

now in these boxes, if I select any item with a text on it, and click on the button, it will copy the items to the other listbox. but if I select any line w/o text, any empty row, and click on the button, it won't change anything. it won't make the other box item empty. here's the code, how I copy the rows.

private void button4_Click(object sender, EventArgs e)
{

    List<int> selectedItemIndexes = new List<int>();
    foreach (string o in listBox1.SelectedItems)
        selectedItemIndexes.Add(listBox1.Items.IndexOf(o));

    for (int i = 0; i < selectedItemIndexes.Count; i++)
    {
        listBox2.Items[selectedItemIndexes[i]] =  listBox1.Items[selectedItemIndexes[i]];
    }

    selectedItemIndexes.Clear();


}

private void button3_Click(object sender, EventArgs e)
{
    List<int> selectedItemIndexes = new List<int>();
    foreach (object o in listBox2.SelectedItems)
        selectedItemIndexes.Add(listBox2.Items.IndexOf(o));

    for (int i = 0; i < selectedItemIndexes.Count; i++)
    {
        listBox1.Items[selectedItemIndexes[i]] = listBox2.Items[selectedItemIndexes[i]];
    }

    selectedItemIndexes.Clear();
}

how can I also copy the empty rows?

War es hilfreich?

Lösung

That is because in following line

foreach (string o in listBox1.SelectedItems) selectedItemIndexes.Add(listBox1.Items.IndexOf(o));

You will get empty string, and it will always return the first index of the empty string.

The solution is to use the selectedIndices as following:

     foreach (int selectedItemInd in listBox1.SelectedIndices)
        {
            selectedItemIndexes.Add(selectedItemInd);
        }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top