Just a beginner asking for guide. :)

private void button2_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                listBox2.Items.Add(listBox1.Items[i]);
                listBox1.Items.Remove(listBox1.Items[i]);
            }
        }

This is the method I made for moving all the items in a listbox to the one next to it. Apparently there's a problem with this code, because when I try out the button, one out of three items in the listBox1 gets left behind for some reason. I don't really have time to make screenshots but here's what happens:

There are three items in listBox1, "Football, Baseball, Basketball", and when I use the button "Baseball" gets left behind. Doing vice versa, as in from listBox2 to 1, out of five items in listBox2(three were original items and the other two were moved from lilstBox1), only three of them get moved, leaving other items in listBox2. I cannot find any pattern in the movements.

I hope to find out what's wrong with my code and also the right code for my purpose. Thanks in advance. :D

Your flow is wrong.
Just slowly think, You first add the value of listbox1[0] to listbox2. and you remove the 0th value,

After you remove listbox1[0]th value, the next value moves up
after incrementing ith value you add the listbox1[1] to listbox2
That's why a value is left out

Ah, I get it now. I probably wasn't thinking enough. I changed the code to this and it worked:

private void button2_Click(object sender, EventArgs e)
        {
            int j = listBox1.Items.Count;
            for (int i = 0; i < j; i++)
            {
                listBox2.Items.Add(listBox1.Items[0]);
                listBox1.Items.Remove(listBox1.Items[0]);
            }
        }

Thanks for the reply.

Mark the thread as solved, and vote up if it helps you!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.