Search code examples
c#winforms.net-2.0

How do I control two listboxes using a Vertical Scrollbar?


I've got a Windows Form that has 6 listboxes in it.

I'm trying to find / make a code that would make them scroll together. So I dropped a Vertical Scroll Bar onto the form, then put in the following code:

private void vScrollR_Scroll(object sender, ScrollEventArgs e)
{
    int i = vScrollR.Value;
    lstcr1.SelectedIndex = i;
    lstpr1.SelectedIndex = i;
    lstsr1.SelectedIndex = i;
    lstcr2.SelectedIndex = i;
    lstpr2.SelectedIndex = i;
    lstsr2.SelectedIndex = i;
}

For some reason though, it won't work (i always returns 0). Am I going about this the wrong way? Is there any other way to achieve what I want? Perhaps, there's a method I need first?

Many thanks to all who will answer.


Solution

  • Change SelectedIndex to TopIndex. I just tried this and it works.

    To keep the UI in sync while updating, you can use Control.BeginUpdate and Control.EndUpdate

            listBox1.BeginUpdate();
            listBox2.BeginUpdate();
            listBox1.TopIndex = 
            listBox2.TopIndex = ++x;
            listBox1.EndUpdate();
            listBox2.EndUpdate();