Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to switch forms in C# using a button event

Tags:

c#

.net

winforms

I have some code here:

private void button1_Click(object sender, EventArgs e)
{
    Application.Run(new Form3());
}

Although I don't think this is how you are meant to change forms, when I ran it, it threw an error stating:

Starting a second message loop on a single thread is not a valid operation

like image 256
Dennis Avatar asked Jun 15 '11 21:06

Dennis


2 Answers

You cannot use Application.Run - that is for starting windows form application (internal message loop which is shared among all forms in the application), not for showing a form. Each form has Show and Hide method so you should simply call:

private void button1_Click(object sender, EventArgs e)
{
    Form3 f = new Form3(); // This is bad
    f.Show();
}

But you should not create form each time you want to show it. If you want to have only one instance of the form you should keep it as global and only show or hide it on demand. Otherwise you will have to call Close instead of Hide to clear all resources the form consumes.

like image 197
Ladislav Mrnka Avatar answered Oct 10 '22 16:10

Ladislav Mrnka


you can do as simple as it is :

test mp = new test();
mp.Text = " Welcome Mr." + textBox1.Text;
this.Hide();
mp.ShowDialog();
this.Close();

where test is your new form and then if you wona pass variables to the other form just make you variable as public then you can make :

 mp.Text = " Welcome Mr." + textBox1.Text;

then showdialog to show your new form and close the old form..

like image 25
Tamer Avatar answered Oct 10 '22 16:10

Tamer