ListBox_Tutorial.zip ( 69.17k )
Number of downloads: 61 Create a List Box with a Context MenuIn this tutorial I will create a simple application that will:
1. Add to a list box from a text box.
2. The list box will display a context menu with list box options
This tutorial comes with a sample application.
I will cover the basics of:
1. Adding a
context menu2. Populating a
list box3. Finding Items in a list box
4. Replace a selected item with another
5. Remove item(s) by index.
6. Change the order of items.
So to setup the Application I have 3 buttons:
One to add Items, One to Search, One to remove Items;
a text box and a list box.
The list box property "SelectionMode" is set to “MultipleExtended"
(I also recommend trying "MultipleSimple" to get a feel for the functionality.)
1. Context MenuThe form load event is where I want to add the context menu.
I want to include in the menu options:
1. Remove Item
2. Move up
3. Move down
A context menu works the same for any basic control; it is added when the control is initialized.
In this case I will use the MyBase.Load event:
CODE
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
AddContextMenu(Me)
End Sub
To create the Context Menu, follow 7 simple steps:
CODE
'Step 1. Declare a New Menu as Class variable---------
Dim myMenu As New ContextMenu()
Private Sub AddContextMenu(ByVal sender As Object)
'Step 2. Declare New Menu Items----------
Dim mnuRemove As New MenuItem
Dim mnuSeparator As New MenuItem
Dim mnuUp As New MenuItem
Dim mnuDown As New MenuItem
'Step 4. Set the Menu Item's text-----------
' Use "&" in front of the letter to make it a
' keyboard shortcut
mnuRemove.Text = "&Remove Items"
' This will make a separator line on the Menu
mnuSeparator.Text = "-"
mnuUp.Text = "Move &Up"
mnuDown.Text = "Move &Down"
'Step 5. Add the Items to the Menu----------
myMenu.MenuItems.Add(mnuRemove)
myMenu.MenuItems.Add(mnuSeparator)
myMenu.MenuItems.Add(mnuUp)
myMenu.MenuItems.Add(mnuDown)
' Step 6. Tell the Items where to go for instructions...(Add the
' Event Handlers)------------------------------------
AddHandler mnuRemove.Click, AddressOf mnuRemove_Click
AddHandler mnuUp.Click, AddressOf mnuUp_Click
AddHandler mnuDown.Click, AddressOf mnuDown_Click
' Step 7. Assign the menu to its owner----------
myListBox.ContextMenu = myMenu
End Sub
A good, robust program, will have several different ways to do the same thing. For instance:
A context menu item such as "Remove" also has a menu strip item, and then a tool bar item, don't forget the keyboard shortcut. So I do not put the routine for removing an item inside the event handler for "mnuRemove.Click", then I would have to write the same code for the other onClick events that are supposed to remove the item; I put the code in its own routine that can be called from the event handlers.
CODE
Private Sub btnRemove_Click(ByVal _
sender As System.Object, ByVal _
e As System.EventArgs) Handles btnRemove.Click
RemoveItems()
End Sub
I do the same for the other Click events in the Context Menu.
So now I have a ListBox with a ContextMenu.
Now let’s tackle some aspects of working with the list box that give people trouble, the list box items.
2. Populate the list box.ListBox's are populated with data type
StringIn the sample application we will enter text into the textbox and click Add.
The Add Button uses this:
CODE
Private Sub AddItem()
'Retrieve string from textBox
Dim strText_Input As String = myTextBox.Text
'Add the new listbox item
myListBox.Items.Add(strText_Input)
'Clear the textbox
myTextBox.Clear()
End Sub
So the listbox function that adds the line to the list box is:
myListBox.Items.Add(strText_Input)In many situations you may want to programmatically add a list or array of data to the list box. You will recursively use the same method; for instance:
CODE
For Each item As String in myStringList
myListBox.Items.Add(item)
Next
‘or
For intIndex As Integer = 0 To myStringArray.Count – 1
myListBox.Items.Add(myStringArray(intIndex))
Next
Now I have a listbox that is populated with items.
3. Find an item in the list box.I will now perform a search of the list box for a value inputted into the text box. In the following code, notice :
For intIndex As Integer = 0 To myListBox.Items.Count – 1I will iterate throught the list box items by index number. The first step is to create a variable that will hold the Index number. The index will start at “0” and count up to “1 less than” the number of items in the box. This is important to remember:
Index starts at 0;
Count starts at 1;
So the highest
index number can only be 1 less than the
CountCode for the Search:
CODE
Private Sub Search()
'Retreive string from textBox
Dim strSearch As String = myTextBox.Text
'If no text is in the textbox, do nothing
If strSearch Is Nothing Then Exit Sub
'Declare a Indexing Variable to iterate
'through the list box items.
For intIndex As Integer = 0 To myListBox.Items.Count - 1
If strSearch = myListBox.Items.Item(intIndex) Then
myListBox.SelectedIndex = intIndex
End If
Next
End Sub
The code accessed each item in the list box and compared it to the strSearch variable which was assigned a value based on the text in the text box. This will select every instance of the searched string.
4. Replace a selected item with another. So now I have selected items from a search. I will go beyond the previous code and replace the found search items with “Found” and the item text.
I will revisit the previous code and add to it:
CODE
For intIndex As Integer = 0 To myListBox.Items.Count – 1
If strSearch = myListBox.Items.Item(intIndex) Then
myListBox.SelectedIndex = intIndex
‘Up to this point the code has been the same
‘as before, but here we add code to replace
‘the selected item
myListBox.Items.Item(intIndex) = _
"Found - " & myListBox.Items.Item(intIndex)
End If
Next
5. Remove item(s) by index. To remove items from a list box I have to first access the collection of items.
This is accomplished with:
myListBox.ItemsmyListBox.SelectedIndices
myListBox.SelectedItems
For more info on Collections go here:
Part 1; Part 2I will iterate through the collection backwards.
“Why Backwards??”
Imagine the collection as a stack of plates. The plate on the bottom is in position “0”. I want to remove plates in position 0 through 2. That is Plates 0, 1, and 2. So I remove plate 0 from the bottom, the next plate, plate 1, is now on the bottom, so it now is in position “0”. As I remove the plates in this manner, every plate changes position with each removal. Now I will start taking plates from the top.... You got it, the plates remain in their positions. Since I am moving down the stack, I can take from the middle and all the plates beneath stay where they are. This is the same as removing from a list box. If the list box has 5 items: 0 – 4; I will count backwards to remove the items I choose.
Follow Along:
CODE
Private Sub RemoveItems()
' I want to store the selected Indices in a List
Dim arrSelected As New List(Of Integer)
' Retrieve Selected Indices
For Each item As Integer In myListBox.SelectedIndices
arrSelected.Add(item)
Next
' How many selected Items are there?
' Then convert that number to an index number
Dim intCount As Integer = arrSelected.Count - 1
' Stepping Backwards I remove the items
For intIndex As Integer = intCount To 0 Step -1
myListBox.Items.RemoveAt(arrSelected(intIndex))
Next
End Sub
Above, arrSelected is a
generic list. I will store only the index numbers of the selected items in this list; therefore, when I iterate through the list like this
arrSelected(intIndex), it represents a number. So in the code above, I am removing items using this:
myListBox.Items.RemoveAt(number). The code above removes any number of selected items.
6. Change the order of items. The bottom two ContextMenu items are:
Move Up
Move Down
In the list box members, I have found no quick method of doing this, so I will have to design my own.
The logical sequence of events will be
1. Access selected items.
2. Store the item and it’s index
3. Remove the item.
4. Add it to a new location.
Follow Along:
CODE
Private Sub MoveUp()
'Retrieve Selected Indices
Dim arrSelected As New List(Of Integer)
For Each item As Integer In myListBox.SelectedIndices
arrSelected.Add(item)
Next
'Get number of selected Items
Dim intCount As Integer = _
arrSelected.Count – 1
'A variable to store the items as we move them.
Dim LB_item As String
' Stepping Forwards we move the items
For intIndex As Integer = 0 To intCount
'If the item is the first in the list
'it cannot move up
If arrSelected(intIndex) > 0 Then
'Store the selected item
LB_item = myListBox.Items.Item( _
arrSelected(intIndex))
'Remove it from the ListBox
myListBox.Items.RemoveAt( _
arrSelected(intIndex))
'Insert it into its new location
myListBox.Items.Insert( _
arrSelected(intIndex) - 1, LB_item)
End If
Next
End Sub
In the “For..Next” code block at the bottom, the code commenting is kind of narrow so I’ll put it here to view a little easier. Since I am moving the items up, I must iterate forward through the list. In moving them, I am first removing, but then replacing, just in a different location, so the higher indices remain in the same location.
For intIndex As Integer = 0 To intCount 'If the item index is 0, it cannot move up, so the code does not execute on that item
If arrSelected(intIndex) > 0 Then 'Store the selected item as a string
LB_item = myListBox.Items.Item(arrSelected(intIndex)) 'Remove it from the ListBox
myListBox.Items.RemoveAt(arrSelected(intIndex)) 'Insert it into its new location. I subtract 1 from the index number to insert it at the lower index
myListBox.Items.Insert(arrSelected(intIndex) - 1, LB_item)
End If
NextRemember, arrSelected(intIndex) represents a number, so arrSelected(intIndex) – 1 is the same as (number – 1).
To move the item down in the list box, I use the same method with 3 small changes.
The iteration; I am changing the direction of the move so I will change the direction of iteration:
For intIndex As Integer = intCount To 0 Step -1The If test; because the highest index cannot go any higher
If arrSelected(intIndex) < myListBox.Items.Count - 1 ThenAnd;
The index modification:
myListBox.Items.Insert(arrSelected(intIndex) + 1, LB_item) Take time to review the sample application. The listbox control has many more members than are covered in this tutorial, so follow the links above for more research. The list iterations and item collections discused in this tutorial are very common place in code writing. They will be transferable to almost any application you write, no matter how simple.
Suggested topics for understanding:
Collections, IEnumerable, IEnumerator, and Generics.
All of these are crucial to great programming.
Until next time.
This post has been edited by dzone41: 29 Oct, 2009 - 04:56 AM