How to Program Two List Boxes to Scroll Together (103809)



The information in this article applies to:

  • Microsoft Visual Basic Standard Edition for Windows 2.0
  • Microsoft Visual Basic Standard Edition for Windows 3.0

This article was previously published under Q103809

SUMMARY

You can give two list boxes the ability to scroll together in unison. In other words, you can program your Visual Basic application so that when the user scrolls the List1 box, the contents of the List2 box will scroll in the same direction automatically -- without using the List2 scroll bar.

MORE INFORMATION

The example below uses two list boxes, side by side, to demonstrate this technique to simulate the appearance of two list boxes scrolling together.

Step-by-Step Example

  1. Start Visual Basic or from the File menu, choose New Project (ALT, F, N) if Visual Basic is already running. Form1 is created by default.
  2. Add two list boxes, one timer control, and one command button to Form1. For the best visual effect, place the list boxes side by side with the List1 box on the left.
  3. Add the following code to the (general) (declarations) section of Form1:
       DefInt A-Z
    						
  4. Add the following code to the Form Load event procedure of Form1:
       Sub Form_Load ()
          'Initialize two list boxes with the alphabet
          For i = 1 To 26
             list1.AddItem Chr$(i + 64)
          Next i
          For i = 1 To 26
             list2.AddItem Chr$(i + 64)
          Next i
          Timer1.Interval = 1
          Timer1.Enabled = True
       End Sub
    						
  5. Add the following code to the Command1 Click event procedure of Form1:
       Sub Command1_Click ()
          End
       End Sub
    						
  6. Add the following code to the Timer1_Timer event procedure of Form1:
       Sub Timer1_Timer ()
          Static PrevTI_List1
          'Get the index for the first item in the visible list
          TopIndex_List1 = list1.TopIndex
          'See if the top index has changed
          If TopIndex_List1 <> PrevTI_List1 Then
             'Set the top index of List2 equal to List1 so that the list boxes
             'scroll to the same relative position
             list2.TopIndex = TopIndex_List1
             'Keep track of the current top index
             PrevTI_List1 = TopIndex_List1
          End If
          'Select the item in the same relative position in both list boxes
          If list1.ListIndex <> list2.ListIndex Then
             list2.ListIndex = list1.ListIndex
          End If
       End Sub
    						
  7. Press the F5 key to run the program. Select a letter in the List1 box. Then try the scroll bar of the List1 box. You should see the same letter highlighted in the List2 box when you select a letter from the List1 box. Then when you try the scroll bar of the List1 box, you should see the List2 box scroll in unison with the List1 box.

Modification Type:MajorLast Reviewed:10/30/2003
Keywords:KB103809