简体   繁体   中英

Open a form in c#

I want to open a new form in C#, so I write:

Form2.Show() 

But Visual Studio tells me this error:

An object reference is required for the non-static field, method, or property Control.Show()

The error is generated because you need to call the Show method on an instance of Form2 class, which means that you need to create an object and call that method on that object:

Form2 form2 = new Form2();
form2.Show();

I really suggest you to learn the theory of Object Oriented Programming in deep, so that you can actually understand what's going on whenever you might encounter such errors.

When a method is not static, you can only use it on an instance of the class.

Form2 form = new Form2();
form.Show();

You Should Create Instance Of Your Form:

 Form2 myForm = new Form2();  
 myForm.Show(); 

You can also ShowDialog Instead Of Show.

Show Displays the form in a non-modal way.
ShowDialog Displays the form in a modal way.

ShowDialog does not. ShowDialog is the same as Show, it just shows the form as a modal window. Modal meaning the form cannot lose focus until it is closed. (The user can't click on other windows within the same application.)

Application.Run starts a message loop for the application and shows the form as the application's main form

Firstly: Reply to the the main questionnaire.

I think you are from Visual Basic .NET background so you are trying to open the form same like Visual Basic .NET way to open form.

In C# you can not open a form like that - you have to make an object of the form first.

Secondly: Reply to answering persons, myForm.show() is used when we are loading the form in any form container.

Form2 myForm = new Form2();  
myForm.ShowDialog();

with the code the form will be opened.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM