The ContextMenuStrip Visual Basic control is a little known example of the new generation of controls available in Visual Basic .NET. This article is a complete explanation to help you learn to use it.
When VB.NET 2005 was introduced, several new "strip" controls were introduced along with it. I wrote about them in this article: New Controls in VB.NET 2005. One of the more interesting new controls is called the ContextMenuStrip control. With this control, you can attach a context menu to other objects, such as the a Windows form, or in the example that will be developed here, a MonthCalendar control.
The MonthCalendar control is one of the handy new controls that makes it easy to manipulate dates. With just one line of code ...
DateSelected.Text = _
e.Start.ToString("MMMM dd, yyyy")
... I can create the default behavior shown below:
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
But suppose I want to allow the user to quickly move to various alternate dates on the calendar. One way to do it would be to add buttons for each type of move.
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
While this works, it takes a lot of room on the form and makes the form busy and confusing. A popup context menu would work great here. In addition getting the clutter away from the main form and making the menu available only when it's needed, the inherently hierarchical structure of menus can be used.
To add one, first add a ContextMenuStrip control to the project. Type in the names of the menu options down and to the right as needed. The "Add" menu structure is shown below.
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
Then bind this control to the MonthCalendar control. This is done by setting the ContextMenuStrip property of the MonthCalendar control as shown below:
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------
The actual code to add a week goes in the Click event of each menu item. The code could look like this:
MonthCalendar.SetDate(DateAdd("d", 7, DateSelectSave))
DateSelectSave = MonthCalendar.SelectionStart
Note that the system creates names for the individual menu items automatically, but they can get a bit out of control. For example, the created name for one in this project was:
SameWeekdayNextMonthToolStripMenuItem
Long names are not really a problem anymore since you seldom have to actually type one with Intellisense to help you, but you can shorten them to something more manageable if you like.
And the finished form looks like this in operation:
--------
Click Here to display the illustration
Click the Back button on your browser to return
--------

