ListBox in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes the ListBox control


ListBox

This control is a list of selectable items, and depending on the control's properties, the user can select one or multiple items.

The control automatically displays scrollbars when needed, unless MultiColumn is True, which prevents displaying of the vertical scrollbar, and rather displays them in multiple columns.

multi column

If you set the ScrollAlwaysVisible property to True, the control displays its vertical scrollbar even if all items fit.

Using the SelectionMode property you can configure the control to let the user select one or more items:

MultiExtended - Multiple items can be selected, and the user can use the SHIFT, CTRL, and arrow keys to make selections

MultiSimple - Multiple items can be selected.

One - Only one item can be selected.

properties

A ListBox takes more room than a ComboBox but can be easier to use if the list is very long.

The following example demonstrates how do you populate ListBox control programmatically:

    Dim mydoc As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
    Dim path As String = IO.Path.Combine(mydoc, "My Web Sites\WebSite1")

    Dim dir As New IO.DirectoryInfo(path)
    ' populate the listbox control
    For Each file As FileInfo In dir.GetFiles
        ' avoid jpg images
        If Not file.Extension = ".jpg" Then
            ListBox1.Items.Add(file.Name)
        End If
    Next


You can also iterate over the Items collection and list the items in the ListBox control named ListBox1:

    For Each item As Object In ListBox1.Items
        ' ToDo: something useful
    Next


To remove the unwanted item(s) you use the following code snippet:

    For i As Integer = ListBox1.Items.Count - 1 To 0 Step -1
        If ListBox1.Items(i).ToString.EndsWith(".jpg") Then
            ListBox1.Items.RemoveAt(i)
        End If
    Next

Previous Lesson | Next Lesson


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.