1

I have two forms i.e. Form A and Form B. If Button X of Form A is clicked only then Form B will show and Form A will hide. I have to do all this in program.cs of a windows Form Application.

Here is the code snipped

            FormA A = new FormA ();
            FormB B = new FormB ();

            A.Show();                    
            if(Button in form A is clicked then )
                  B.Show() and A.hide();
            else 
                  application.close()
2
  • 1
    Could you show more about the point where you are using this code? Is it inside the Main function? Commented May 10, 2020 at 19:29
  • Yes Exactly Steve. It is inside the private static void Main() { ............... } block Commented May 10, 2020 at 19:32

1 Answer 1

1

First thing required is to have the button visible outside the form class.
This is done setting the Modifier property in the WinForms Designer to public, or, if you create the button programmatically, you need to declare the variable public at the form level.

Now, with the button public you could write an event handler for its click event and write that handler inside the Program.cs class.
This also requires that your FormA and FormB variables are usable inside the event handler of the button, so you need to have also them public.

public static class Program
{
    static FormA A;
    static FormB B;

    public static void Main()
    { 

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        A = new FormA();
        B = new FormB();
        A.Button1.Click += onClick;    

        // This should show the A instance
        Application.Run(A);
        ....
    }
    public static void onClick(oject sender, EventArgs)
    {
        A.Hide();
        B.Show();
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your answer. I will mark it correct as soon as it works :)
Steve, Are you sure we can access static class event like you did in the answer ?
Sorry, written by hand and forget to add static to the event handler
Thanks you are genius but one thing, is there any other way to beside Application.Run for FormA. This is only because I have to start a kernel using application run after run. Thanks in Advance :)
Thanks for your comment telling me how to accept the answer and yes you are right I should question with some more details :) thanks
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.