C# dynamically add event handler

后端 未结 5 792
感动是毒
感动是毒 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:18

    are you asking for the signature for the click event? if you're working in visual studio, you should be able to type

    item.Click+= tab tab

    and it'll generate something for you

    0 讨论(0)
  • 2020-12-17 09:23

    try:

     /* HERE IS WERE I NEED HELP */
    
     item.Click += new EventHandler(toolStripClick);
    

    actual handler:

    void toolStripClick(object sender, EventArgs e)
    {
         ToolStripItem item = (ToolStripItem)sender;
         MessageBox.Show(item.Text);
    }    
    
    0 讨论(0)
  • 2020-12-17 09:34

    I would recommend you look into subscriptions for events. In the event you have to make sure it's the last item in the menu item.
    Look at MSDN's help for the item

    0 讨论(0)
  • 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); };
    
    0 讨论(0)
  • 2020-12-17 09:45

    Well, if I understand your question correctly, your "needs help" section should become this:

    item.Click += new EventHandler(item_click);
    

    then you just need to add a function to your class:

    public void item_click(object sender, EventArgs e)
    {
       //do stuff here
    }
    
    0 讨论(0)
提交回复
热议问题