0

我有一个带有主键索引和 strUsername 的数据库行,我正在使用它们在菜单条中动态生成下拉项。该代码将用户名字符串作为文本值提供给下拉项,并创建一个事件处理程序。我想将主键整数传递给单击事件方法,但我得到的代码为所有单击事件方法提供了数据库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();
    }
}
4

1 回答 1

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);
}
于 2013-02-08T19:23:27.867 回答