-4

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()

Dale K
  • 25,246
  • 15
  • 42
  • 71
Ayman
  • 25
  • 2
  • Does this answer your question? [C# error: "An object reference is required for the non-static field, method, or property"](https://stackoverflow.com/questions/10264308/c-sharp-error-an-object-reference-is-required-for-the-non-static-field-method) – Progman Nov 16 '19 at 11:38
  • 1
    You might favor VB.NET, it allows this kind of syntax. But not C#, Show() is not a static method so you must use a proper object reference. var frm = new Form2(); frm.Show(); – Hans Passant Nov 16 '19 at 11:41
  • Do you create a new instance of `Form2` before trying to access it? –  Nov 16 '19 at 11:43
  • @Ayman, please consider to mark one of the answers below as accepted if it has resolved your issue. – Kenna Nov 19 '19 at 14:15

3 Answers3

4

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.

Kenna
  • 302
  • 4
  • 15
2

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

Form2 form = new Form2();
form.Show();
Ahmed Tounsi
  • 1,482
  • 1
  • 14
  • 24
0

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71