School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,099 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 2,035 people online right now. Registration is fast and FREE... Join Now!




ListBox with a Context Menu

 
Reply to this topicStart new topic

> ListBox with a Context Menu, Manipulate items in a list box that displays a context menu. Add, remo

dzone41
Group Icon



post 27 Oct, 2009 - 04:32 PM
Post #1


Attached File  ListBox_Tutorial.zip ( 69.17k ) Number of downloads: 61
Create a List Box with a Context Menu

In 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 menu
2. Populating a list box
3. 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 Menu
The 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 String
In 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 – 1
I 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 Count
Code 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.Items
myListBox.SelectedIndices
myListBox.SelectedItems

For more info on Collections go here: Part 1; Part 2
I 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
Next

Remember, 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 -1

The If test; because the highest index cannot go any higher
If arrSelected(intIndex) < myListBox.Items.Count - 1 Then


And;
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
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 12:10PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month