VB.Net - ListBox Control



vb.net-listbox.jpg


VB.Net provides several mechanisms for gathering input in a program. A Windows Forms ListBox control displays a list of choices which the user can select from.

You can use the Add or Insert method to add items to a list box. The Add method adds new items at the end of an unsorted list box. The Insert method allows you to specify where to insert the item you are adding.

ListBox1.Items.Add("Sunday")

 

The SelectionMode property determines how many items in the list can be selected at a time. A ListBox control can provide single or multiple selections using the SelectionMode property .

If you want to retrieve a single selected item to a variable , you can code like this.

Dim var As String

var = ListBox1.SelectedItem

 

If you change the selection mode property to multiple select , then you will retrieve a collection of items from ListBox1.SelectedItems property.

ListBox1.SelectionMode = SelectionMode.MultiSimple

 

The following VB.Net program initially fill seven days in a week while in the form load event and set the selection mode property to MultiSimple. At the Button click event it will display the selected items.

Public Class Form1
  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    ListBox1.Items.Add("Sunday")
    ListBox1.Items.Add("Monday")
    ListBox1.Items.Add("Tuesday")
    ListBox1.Items.Add("Wednesday")
    ListBox1.Items.Add("Thursday")
    ListBox1.Items.Add("Friday")
    ListBox1.Items.Add("Saturday")

    ListBox1.SelectionMode = SelectionMode.MultiSimple
  End Sub

  Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim obj As Object
    For Each obj In ListBox1.SelectedItems
      MsgBox(obj.ToString)
    Next

  End Sub
End Class

Next Post Previous Post
No Comment
Add Comment
comment url