In this tutorial we want to see how to perform CRUD operations with a ListBox as our Control. This is a windows forms listbox CRUD tutorial and example. The aim is ADD UPDATE DELETE and CLEAR items to and off a ListBox control.
We have a TextBox for entering data to the ListBox. That data gets inserted to ListBox on us clicking the Add button.
We listen to selectedIndexChanged events for the ListBox and set the ListBox's selected item to the TextBox. From there we can easily update the ListBox by clicking the update button.
On the other hand we can also delete the selected item just by clicking the delete button. Also we clear items, everything off the ListBox by clicking the Clear button.
We are Building a Vibrant YouTube Community
We have a fast rising YouTube Channel of friends. So far we've accumulated more than 2.6 million agreggate views and more than 10,000 subscribeers. Here's the Channel: ProgrammingWizards TV.
Please go ahead subscribe(free obviously) as well. If you have a question or a comment you can post there instead of in this site.People are suggesting us tutorials to do there so you can too.
Here's this tutorial in Video Format.
Let's start.
Program.vb
Let's Import Namespaces
Before we import our namespaces, right click your VB.NET project, then choose Add references
, the search System.Windows.Forms
namespace and add it to your project.
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Then add the following imports at the top of your file.
In VB.NET normally we add imports using the Imports
keyword.
Create our Module
We create our module to encapsulate our code:
Module Program
Define our Data Members
We will have these private data members or fields in ourr module:
Private WithEvents myListBox As ListBox
Private nameTxt As TextBox
Private WithEvents addBtn As Button
Private WithEvents updateBtn As Button
Private WithEvents deleteBtn As Button
Private WithEvents clearBtn As Button
Private myForm As Form
ListBox
- ListBox will display our items in a list. Users can select items. We supply it with theWithEvents
modifier since this ListBox will support event handling.TextBox
- Users will enter data via the TextBox.Button
:addBtn
- users will click this button to add data to our ListBox. This and other buttons support events so we specify theWithEvents
modifier.Button
:updateBtn
- users will click this button to update data that is selected in the listbox with data that has been typed in the TextBox.Button
:deleteBtn
- users will click this button to delete the data that is selected in the ListBox.Form
- To hold all other controls.
How to create VB.NET Windows Forms Components
Let's see how to programmatically create VB.NET windows forms components programmatically.
Firts we define a subroutine to do so:
Sub createComponents()
....
Then we start by instantiating the Label class:
Dim nameLabel As Label = New Label With {
.Location = New Point(431, 137),
.Size = New Size(45, 19),
.Text = "Name"
}
As you can see we've passed the Location property, Size and Text.
Then we create a TextBox by instantiating the TextBox class:
nameTxt = New TextBox With {
.Location = New Point(517, 137),
.Size = New Size(194, 23),
.TabIndex = 0
}
Then we do the same thing with our buttons:
addBtn = New Button With {
...
}
updateBtn = New Button With {
...
}
deleteBtn = New Button With {
...
}
clearBtn = New Button With {
...
}
Then we instantiate our ListBox class to create it:
myListBox = New ListBox With {
.Location = New Point(24, 90),
.Size = New Size(400, 350)
}
Finally we add these controls to our Controls
property of our Form
class:
myForm.Controls.Add(clearBtn)
myForm.Controls.Add(deleteBtn)
myForm.Controls.Add(updateBtn)
myForm.Controls.Add(addBtn)
myForm.Controls.Add(nameTxt)
myForm.Controls.Add(nameLabel)
myForm.Controls.Add(myListBox)
and end or close our subroutine:
End Sub
How to Clear our VB.NET TextBox
Well we just set the Text
property to empty:
Private Sub clearTxts()
nameTxt.Text = ""
End Sub
How to set Selected VB.NET ListBox Item to TextBox
First we need to create an event handler that listens to SelectedIndexChanged
event. Typically event handlers take a System.Object
and a System.EventArgs
object as parameters.
Don't forget to specify the event it will be handling.
Private Sub myListBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myListBox.SelectedIndexChanged
Then we check if an item is actually selected with an If statement:
If myListBox.SelectedItem IsNot Nothing Then
...
End If
If so we set cast the SelectedItem
property of the ListBox to a string then set it to the TextBox:
nameTxt.Text = myListBox.SelectedItem.ToString()
You do this in the If statement.
How to add a TextBox Item to VB.NET ListBox
First let's listen to the add button
click event:
Private Sub addBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles addBtn.Click
....
Then just invoke the Add()
method, passing in the value or Text
property of the nameTxt
textbox.
We will then set the selected item to the value that was typed in the nameTxt
TextBox.
myListBox.SelectedItem = nameTxt.Text
afterwhich we clear the TextBox:
clearTxts()
Then close our subroutine.
End Sub
How to Update Selected ListBox Item from TextBox in VB.NET
To update an item first it has to be selected. This will raise an SelectedIndexChanged
event of our ListBox. Remember our ListBox supports events since we had declared it with the WithEvents
modifier.
The selected item will be set to the TextBox as we had seen.
Then we listen to updateBtn
button click event.
Private Sub updateBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles updateBtn.Click
...
First we check if selected listbox index is not -1
:
If myListBox.SelectedIndex <> -1 Then
...
Then we get the selected index value using ListBox's SelectedIndex
property:
Dim selectedIndex As Integer = myListBox.SelectedIndex
Then remove the item at that position/index:
myListBox.Items.RemoveAt(selectedIndex)
And insert a new one at the same position:
myListBox.Items.Insert(selectedIndex, nameTxt.Text)
How to Delete Selected ListBox Item in VB.NET
First the item will be selected such that we will be able to get the index of the selected item.
We will listen then to deleteBtn
button click events:
Private Sub deleteBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles deleteBtn.Click
...
Then check that the selected index is not -1
:
If myListBox.SelectedIndex <> -1 Then
...
If this evaluates to true we continue, getting the selected index:
Dim selectedIndex As Integer = myListBox.SelectedIndex
Then simply remove the item at at that SelectedIndex
with RemoveAt()
method:
myListBox.Items.RemoveAt(selectedIndex)
Programmatically Creating VB.NET Form
Well we first define a subroutine:
Private Sub createForm()
....
To create a Form you simply instantiate the System.Windows.Forms.Form
class, then set the Form properties via Object Initializer syntax:
myForm = New Form With {
.Text = "VB.NET WinForms ListBox : CRUD - ADD UPDATE DELETE",
.ClientSize = New Size(734, 484),
.BackColor = Color.LightSeaGreen
}
Then we create the Form controls:
createComponents()
Then enable the application visual styles and run the form:
Application.EnableVisualStyles()
Application.Run(myForm)
Here's the full code:
Full Code
Imports System
Imports System.Drawing
Imports System.Windows.Forms
Module Program
' Data Members
Private WithEvents myListBox As ListBox
Private nameTxt As TextBox
Private WithEvents addBtn As Button
Private WithEvents updateBtn As Button
Private WithEvents deleteBtn As Button
Private WithEvents clearBtn As Button
Private myForm As Form
'Create Components
Sub createComponents()
Dim nameLabel As Label = New Label With {
.Location = New Point(431, 137),
.Size = New Size(45, 19),
.Text = "Name"
}
nameTxt = New TextBox With {
.Location = New Point(517, 137),
.Size = New Size(194, 23),
.TabIndex = 0
}
addBtn = New Button With {
.Location = New Point(431, 284),
.Size = New Size(83, 31),
.Text = "ADD",
.TabIndex = 2
}
updateBtn = New Button With {
.Location = New Point(587, 284),
.Size = New Size(83, 31),
.Text = "UPDATE",
.TabIndex = 3
}
deleteBtn = New Button With {
.Location = New Point(431, 361),
.Size = New Size(83, 31),
.Text = "DELETE",
.TabIndex = 4
}
clearBtn = New Button With {
.Location = New Point(587, 361),
.Size = New Size(83, 31),
.Text = "CLEAR",
.TabIndex = 5
}
myListBox = New ListBox With {
.Location = New Point(24, 90),
.Size = New Size(400, 350)
}
myForm.Controls.Add(clearBtn)
myForm.Controls.Add(deleteBtn)
myForm.Controls.Add(updateBtn)
myForm.Controls.Add(addBtn)
myForm.Controls.Add(nameTxt)
myForm.Controls.Add(nameLabel)
myForm.Controls.Add(myListBox)
End Sub
'Clear TextBox
Private Sub clearTxts()
nameTxt.Text = ""
End Sub
' ListBox SelectionChanged Event Handler
Private Sub myListBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles myListBox.SelectedIndexChanged
If myListBox.SelectedItem IsNot Nothing Then
nameTxt.Text = myListBox.SelectedItem.ToString()
End If
End Sub
' Add Button Click event handler
Private Sub addBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles addBtn.Click
myListBox.Items.Add(nameTxt.Text)
myListBox.SelectedItem = nameTxt.Text
clearTxts()
End Sub
' Update button click event handler
Private Sub updateBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles updateBtn.Click
If myListBox.SelectedIndex <> -1 Then
Dim selectedIndex As Integer = myListBox.SelectedIndex
myListBox.Items.RemoveAt(selectedIndex)
myListBox.Items.Insert(selectedIndex, nameTxt.Text)
Else
MessageBox.Show("Please Select an Item to Update First", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
' Delete button click event handler
Private Sub deleteBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles deleteBtn.Click
If myListBox.SelectedIndex <> -1 Then
Dim selectedIndex As Integer = myListBox.SelectedIndex
myListBox.Items.RemoveAt(selectedIndex)
clearTxts()
Else
MessageBox.Show("Please Select an Item to Delete First", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End Sub
' Clear Button click event handler
Private Sub clearBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles clearBtn.Click
myListBox.Items.Clear()
clearTxts()
End Sub
' Create VB.NET Windows Form and Run it
Private Sub createForm()
myForm = New Form With {
.Text = "VB.NET WinForms ListBox : CRUD - ADD UPDATE DELETE",
.ClientSize = New Size(734, 484),
.BackColor = Color.LightSeaGreen
}
createComponents()
Application.EnableVisualStyles()
Application.Run(myForm)
End Sub
' Main sub routine
Sub Main()
createForm()
End Sub
End Module
Result
Running The Project
- Create a console application.
- Then paste the above code.
- Go to your projects properties(by right clicking project name and choosing properties), and change application type to Windows Forms.
Best Regards.