[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Display a horizontal scrollbar in a ListBox in C#

[Display a horizontal scrollbar in a ListBox in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.