Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Call a button click event from another form

Options
  • 09-08-2011 10:57am
    #1
    Registered Users Posts: 4,012 ✭✭✭


    I have a C# windows app which has two forms.
    I want to call a button click event which is on Form A from a separate form (Form B). The problem is the button is declared as private on Form A so I can't get at it from Form B
    I have looked at reflection as a way to do this but don't know much about it.


Comments

  • Closed Accounts Posts: 25 iDigian


    To the best of my knowledge (it's from memory so don't earbash me if it's wrong) you could do it using reflection as follows,

    overload the constructor for your form to pass in the reference to the form you want to call the click on.

    So if you have two forms form1 and form2 and you want to call a method on form1 from form2 you would overload the constructor of form2 as follows,

    public Form2(Form formObj, string callMethod)
    {
    InitializeComponent();
    MethodInfo metInf = formObj.GetType().GetMethod(callMethod);
    // Check to make sure methodinfo is not null
    if (metInf!=null)
    {
    metInf.Invoke(formObj, new object[]{});
    }
    }

    Note the line : metInf.Invoke(formObj, new object[]{});

    You will need to specify the parameters of the method you want to invoke.



Advertisement