我有一个带有主键索引和strUsername的数据库行,我正在使用它们来动态生成菜单条中的下拉项。代码为下拉项提供用户名字符串作为文本值并创建事件处理程序。我想将主键整数传递给click事件方法,但我得到的代码为所有click事件方法提供了数据库row.count
值。有人可以帮忙吗?
// Generate drop down items from database
daUsers.Fill(dtUsers);
// Update mnuFileNew drop down list
if (dtUsers.Rows.Count != 0)
{
mnuFileNew.DropDownItems.Clear();
foreach (dbAutoBloggerDataSet.dbTblUsersRow row in dtUsers.Rows)
{
ToolStripMenuItem newItem = new ToolStripMenuItem(row.strUsername);
newItem.Click += new EventHandler((sender, e) => mnuFileNewUser_Click(sender, e, row.nId));
mnuFileNew.DropDownItems.Add(newItem);
}
}
// Drop down item event handler
private void mnuFileNewUser_Click(object sender, EventArgs e, int nId)
{
frmLogin frmLogin = new frmLogin(nId);
DialogResult result = frmLogin.ShowDialog();
if (result == DialogResult.OK)
{
frmProfile frmProfile = new frmProfile(frmLogin.nId);
frmProfile.ShowDialog();
screenRefresh();
}
}
答案 0 :(得分:0)
我认为此示例代码很有用
void AddMenuItem(string text, string action)
{
ToolStripMenuItem item = new ToolStripMenuItem();
item.Text = text;
item.Click += new EventHandler(item_Click);
item.Tag = action;
//first option, inserts at the top
//historyMenu.Items.Add(item);
//second option, should insert at the end
historyMenuItem.DropDownItems.Insert(historyMenuItem.DropDownItems.Count, item);
}
private void someHistoryMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
string args = menuItem.Tag.ToString();
YourSpecialAction(args);
}