C# dynamically add event handler

后端 未结 5 795
感动是毒
感动是毒 2020-12-17 08:40

Hi i have a simple question. here is my code:

        XmlDocument xmlData = new XmlDocument();
        xmlData.Load(\"xml.xml\");

        /* Load announceme         


        
5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 09:37

    You could use the Tag property of the ToolStripMenuItem:

    item.Tag = Announcements[i].LastChild.InnerText;
    
    public void item_click(object sender, EventArgs e)
    {
        var menu = sender as ToolStripMenuItem;
        if (menu!= null)
            MessageBox.Show(menu.Tag);
    }
    

    Or you could use a lambda, which will capture the variable:

    string data = Announcements[i].LastChild.InnerText;
    item.Click += (s, e) => { MessageBox.Show(data); };
    

提交回复
热议问题