Display a horizontal scrollbar in a ListBox in C#

[horizontal scrollbar]

Displaying a horizontal scrollbar is easy but useful. If you need to display some long values in a ListBox, you may want to be able to scroll to the right to see the ends of the values. For example, this program displays the names of the files in its application directory. On my system, the files are in a deep directory hierarchy so all of the values begin with the same long path. It’s much more useful to see the file names rather than the shared path.

To display the horizontal scroll bar, simply set the ListBox control’s HorizontalScrollbar property to true. You can do this at design time or at run time as shown in the following code.

private void Form1_Load(object sender, EventArgs e)
{
    lstFiles.HorizontalScrollbar = true;
    lstFiles.DataSource =
        Directory.GetFiles(Application.StartupPath);
}

This code sets the HorizontalScrollbar property and then makes the ListBox display the names of the files in the application’s startup directory.

Note that the ListBox only displays the scroll bar when it is necessary. If the values in the ListBox are short enough to fit, the scroll bar doesn’t appear. (Actually the control allows a bit of extra space so it may appear when it strictly doesn’t need to. The control seems to be trying to allow enough room for a vertical scroll bar in case that is needed. You get the idea, though.)


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, user interface and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.