Using Listbox Control in vb.net

This article will let us considered how to add and remove operations are used to move the items from one listbox to antoher.
  • 5682
 

List Box control is frequently used in applications. Here, we learn how to use list box control in vb.net. In the given example add & remove operations will be performed on listbox1 and listbox2 to move items from one listbox to another.

 

Code

 

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.ObjectByVal e As System.EventArgsHandlesMyBase.Load

        Try

            ' Adding items to Listbox1

            ListBox1.Items.Add("Amit")

            ListBox1.Items.Add("Sumit")

            ListBox1.Items.Add("Ramit")

            ListBox1.Items.Add("Kapil")

            ListBox1.Items.Add("Sahil")

        Catch ex As Exception

        End Try

    End Sub

 

    Private Sub Button3_Click(ByVal sender As System.ObjectByVal e As System.EventArgs)Handles Button3.Click

        Me.Close()

    End Sub

 

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

        Try

            If ListBox1.Text = "" Then

                MsgBox("ListBox1: Please select an item first..")

            Else

 

                Dim a As Integer

                ' variable 'a' will contain the index of the selected item

                a = ListBox1.Items.IndexOf(ListBox1.Text)

                ' code to add item to listbox2

                ListBox2.Items.Add(ListBox1.Items.Item(a))

                ' code to remove item from listbox1

                ListBox1.Items.Remove(ListBox1.Items.Item(a))

            End If

        Catch ex As Exception

        End Try

    End Sub

 

    Private Sub Button2_Click(ByVal sender As System.ObjectByVal e As System.EventArgs)Handles Button2.Click

        Dim a As Integer

        Try

            If ListBox2.Text = "" Then

                MsgBox("ListBox2: Please select an item first..")

            Else

                a = ListBox2.Items.IndexOf(ListBox2.Text)

                'code to add item to listbox1

                ListBox1.Items.Add(ListBox2.Items.Item(a))

                'code to remove item from listbox2

                ListBox2.Items.RemoveAt(a)

            End If

        Catch ex As Exception

        End Try

    End Sub

End Class

 

Output

 

View of application on load

 listbox1.gif

We can move items from one listbox to another as shown in below figure

 listbox2.gif

If you don't select any item and click on move button then such a message will appear 

listbox3.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.