Oct 14, 2010

Building a C# context menu at runtime

I know this is a very basic topic, but I'm pretty sure someone will find a use for it.
This example takes a result set (res.Rows) and builds a context menu with hyperlinks loaded in the tag property. When you click on the menu item, it that loads the link in a webbrowser control. Remember to set the context menu property of the control you want to associate the menu with. The code is self-explanatory.

foreach (DataRow r in res.Rows)
ToolStripMenuItem mnuItem = new ToolStripMenuItem();

mnuItem.Text = r[1].ToString();
mnuItem.Tag = @"http://serverIP/website/" + r[3].ToString();
mnuItem.Image = Properties.Resources.ImageName;

mnuItem.Click += new EventHandler(ContextMenuItemClick);

private void ContextMenuItemClick(object sender, EventArgs e)
ToolStripMenuItem clicked = sender as ToolStripMenuItem;

No comments: