This article may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. To maintain the flow of the article, we've left these URLs in the text, but disabled the links.

Visual Studio 6.0
March 2000

Programmatically Scroll a Listview Control to the Selected Item

by Mike D. Jones

As you know, the listview control provides a great way to associate items with icons, pictures, or in report rows. This control makes it easy to programmatically select an item in the list. However, just because Visual Basic selects an item, doesn't always mean that it will be visible to a user. For example, if you have many items displayed in the control, you'd normally need to use the scroll bar to display an item at the bottom of the list.

Fortunately, the listview control also makes it easy to programmatically scroll to a selected item. Each list item has an EnsureVisible method. Just as you would expect, when you call this method, it forces the control to display the item in the visible portion of the listview.

Come out, come out wherever you are

To illustrate, let's create a quick example. First, launch a new project in Visual Basic. Next, select Project | Components from the menu bar, and select Microsoft Common Controls 6.0 from the list. Click OK to add the listview control to the toolbar. Now, drop a listview control onto the default form. To make life easier, we'll use the control in Report view. To do so, we'll need to add at least one column to the control.

Right-click on the listview and select Properties from the shortcut menu. In the Properties Pages dialog box, change the control's View property to 3 - lvwReport. Next, click on the Column Headers tab, click Insert Column, and enter the information shown in Figure A. Click OK to complete the process.

Figure A: We added a single column to the listview's Report view.
[ Figure A ]

Now, as our last step, we'll add the code to populate the listview, then select the last item in the list and display it. To do so, right-click on Form1 and select View Code from the shortcut menu. When the IDE displays the code window, use the Object and Procedure dropdown lists to select the Form's Load event. Now, enter the code from Listing A and run the project. When you do, Visual Basic opens the form and displays the 20th item in this list.

Listing A: Code to display a selected item

Private Sub Form_Load() 
      Dim x As Integer
      With ListView1
      For x = 1 To 20
      .ListItems.Add Key:="foo" & x, Text:="foo" & x
      Next x
      .SelectedItem = .ListItems("foo20")
      End With
      End Sub

Copyright © 2000, ZD Inc. All rights reserved. ZD Journals and the ZD Journals logo are trademarks of ZD Inc. Reproduction in whole or in part in any form or medium without express written permission of ZD Inc. is prohibited. All other product names and logos are trademarks or registered trademarks of their respective owners.