示例代码:
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//添加菜单一
ToolStripMenuItem subItem;
subItem = AddContextMenu("新闻", contextMenuStrip1.Items, null);
//添加子菜单
AddContextMenu("今日要闻", subItem.DropDownItems, new EventHandler(MenuClicked));
AddContextMenu("今日关注", subItem.DropDownItems, new EventHandler(MenuClicked));
//添加菜单二
subItem = AddContextMenu("笑话", contextMenuStrip1.Items, null);
//添加子菜单
AddContextMenu("现代笑话", subItem.DropDownItems, new EventHandler(MenuClicked));
AddContextMenu("古代笑话", subItem.DropDownItems, new EventHandler(MenuClicked));
}
///
/// 添加子菜单
///
/// 要显示的文字,如果为 - 则显示为分割线
/// 要添加到的子菜单集合
/// 点击时触发的事件
///
ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback)
{
if (text == "-")
{
ToolStripSeparator tsp = new ToolStripSeparator();
cms.Add(tsp);
return null;
}
else if (!string.IsNullOrEmpty(text))
{
ToolStripMenuItem tsmi = new ToolStripMenuItem(text);
if (callback != null) tsmi.Click += callback;
cms.Add(tsmi);
return tsmi;
}
return null;
}
void MenuClicked(object sender, EventArgs e)
{
MessageBox.Show("You Clicked Menu Item [" + ((sender as ToolStripMenuItem).Text) + "]");
}
先写个子方法,根据variable name读数据库好了