6.7 Force a List Box to Scroll


Problem

You need to scroll a list box programmatically so that certain items in the list are visible.

Solution

Set the ListBox.TopIndex property, which sets the first visible list item.

Discussion

In some cases, you might have a list box that stores a significant amount of information or one that you add information to periodically. It's often the case that the most recent information, which is added at the end of the list, is more important than the information at the top of the list. One solution is to scroll the list box so that recently added items are visible.

The following example form includes a list box and a button that adds 20 items to the list and then scrolls to the last full page using the TopIndex property.

 using System; using System.Windows.Forms; public class ListBoxScrollTest : System.Windows.Forms.Form {     // (Designer code omitted.)     int counter = 0;     private void cmdTest_Click(object sender, System.EventArgs e) {              for (int i = 0; i < 20; i++) {                      counter++;             listBox1.Items.Add("Item " + counter.ToString());         }         listBox1.TopIndex = listBox1.Items.Count - 1;     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net