Adding an eventhandler to a control created at runtime

I need some help.

I'm creating an application where I add control on runtime to a form. This works fine and I can set all the properties I want. But my problem is how to add a procedure to those controls. I have several controls using the same procedure for handling some specific events (e.g. MouseUp, MouseDown).

Can somebody provide a sample or some hints how to solve this



Answer this question

Adding an eventhandler to a control created at runtime

  • tc ace

    Hi,
    if you want to add a new event handler to your component do something like this:

    myControl.MouseDown += new System.Windows.Forms.MouseEventHandler(this.myControl_MouseDown);

    and then define your event handler:
    private void myControl_MouseDown(object sender, MouseEventArgs e)
    {
    ...
    }



  • PhilW

    In VB.net:

    First, create a method to handle the event. In the case of MouseUp:

    Private Sub MyControl_MouseUp(ByVal sender as Object, ByVal e as MouseEventArgs)

    ...

    End Sub

    Then when you create your control at runtime, simply wire up the event handler:

    AddHandler MyControl.MouseUp, AddressOf MyControl_MouseUp

    Tony


  • Sugi

    Thanks a lot, this works perfect.

    Regards,
    Simon


  • DarkoSK

    i didnt get the code u have given

    so will u please write it more details please and for my problem please refer to reply i made

    tHanks

    sandy



  • Bill_Gates

    hi

    this code is ok for me. but my problem is different.

    i have added the datagrid to my page dynamically and binding it to database.

    and now i want to add an event like i want to sort the column by cllicking on the header.....so how do i add the event dynamically at the runtime

    please help



  • Adding an eventhandler to a control created at runtime