The PopupMenu library module
Before starting, we have to create a module that will contain all the methods we will write to extend the control. Let's call it
myPopupMenuLib. It will contains all of our extend methods for the
PopupMenu control, and the extending methods ( i.e. the ones that use the
Extends keyword ) have to be defined as
The first method is called
SetByItem(). You pass a string, and if there is an item matching that string, then the PopupMenu's selection is set to this item. The code is pretty straightforward. It loops through all the menu's items, compare each of them to the passed string and if a match is found, then the menu's selection is set to this item en the method is exited. If there is no match found, then the menu is set to no selection.
Sub SetByItem(Extends extMenu As PopupMenu, inStringToMatch As String) //-- Sets the menu to the item matching the passed string // If no match is found, sets the menu with no selection. Dim theLastIndex As Integer = extMenu.ListCount-1 // Search for an item matching the passed string For i As Integer = 0 To theLastIndex If extMenu.List( i ) = inStringToMatch Then // -- We found a match -- // Set the menu to this row extMenu.ListIndex = i // We're done Return End If Next // -- No match was found -- // Set the menu with no selection extMenu.ListIndex = -1 End Sub
Note that the code will stop at the first matching item it encounters, even if there is more than one of them.
Using the RowTag property
When the items populating a
PopupMenu come from a database, I like to store the database row ID of the item in the
PopupMenu.RowTag property in order to get it back without querying the database. In some case, It's useful to be able to set the menu's selection with a given Rowtag value.
The code below work pretty much as does the code above, except that it's testing against the
RowTag property, which is a
Variant. Hence the use of the
Variant.Equals() method to compare the two values.
Sub SetByRowTag(Extends extMenu As PopupMenu, inTag As Variant) //-- Sets the PopupMenu by finding the first occurence of inTag in the rowTags Dim theLastIndex As Integer = extMenu.ListCount - 1 // Search for a row tag matching the passed value For i As Integer = 0 To theLastIndex If extMenu.RowTag( i ).Equals( inTag ) Then // -- We found a match -- // Set the menu's selection to this row extMenu.ListIndex = i // We're done Return End If Next // No match was found extMenu.ListIndex = -1 End Sub
As for the
SetByItem() method, the code will stop at the first matching row tag it encounters, even if there is more than one of them.
We're done for this week. Fell free to comment or to ask any question you may have. Next week we'll continue to extend the PopupMenu class by populating it with the data from a