Jump to content







- - - - -

Add child items to ToolStripMenuItem using C# – C Sharp

  Posted by Barnsite, 22 January 2013 · 2,959 views

I wanted to be able to populate menu items from a database, i.e. I had a Print Document top level menu item and I wanted to be able to populate the children from the database dynamically with each available document.
The theory was this:
1. Use the MouseHover event for the main menu item
2. When the user hovers over the item, get the list of documents and add them as children
3. Add a Click event handler to process clicks on the children
Below is the MouseOver code (NB I’ve replaced the load from database code with three simple allocations to simplify the code). Notice that the property that holds the menu item children is DropDownItems.

private void MyToolStripMenuItem_MouseHover(object sender, EventArgs e)
{
//create tsParent using sender
ToolStripMenuItem tsParent = (ToolStripMenuItem)sender;


//check to see if the children have already been created
//(stops them being added repeatedly if you hover more than once)

if (tsParent.DropDownItems.Count == 0)
{
//define new ToolStripMenuItem to use as the new child
ToolStripMenuItem newChild;

//in the real case this is a loop adding items from a database
//notice the Click event handler added to each item detailed below
newChild= new ToolStripMenuItem();
newChild.Text = "Added Item One";
newChild.Tag = 1;
newChild.Click += new EventHandler(processMeunItem);
//add the new child to the parent DropDownItems collection
tsParent.DropDownItems.Add(newChild);

newChild= new ToolStripMenuItem();
newChild.Text = "Added Item 2";
newChild.Tag = 2;
newChild.Click += new EventHandler(processMeunItem);
tsParent.DropDownItems.Add(newChild);

newChild= new ToolStripMenuItem();
newChild.Text = "Added Item 3";
newChild.Tag = 3;
newChild.Click += new EventHandler(processMeunItem);
tsParent.DropDownItems.Add(newChild);
}
}

The code above will add three children to the menu item when you hover over it. Now we need to do something when a child is clicked:

//code runs when any of the new children are clicked
private void processMeunItem(object sender, EventArgs e)
{
//Get the tag of the selected menu item and assign to integer selectedMenuTag
int selectedMenuTag = Convert.ToInt32(((ToolStripMenuItem)sender).Tag);

//do something with the selected item...
}

This will allocate the Tag of the clicked item to selectedMenuTag, you can then use it for further processing.
http://feeds.wordpre...dpress.com/553/ Posted Image

Source

  • 0




Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

April 2014

S M T W T F S
  12345
6789101112
13141516 17 1819
20212223242526
27282930   

My Picture

0 user(s) viewing

0 members, 0 guests, 0 anonymous users

Categories