Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# Show Windows Form

Tags:

c#

.net

winforms

So, I'm struggling a little bit here. I am writing a windows console application in C# and have just made a login form for the application called frmLogin. I tried using the MS documented method of;

Form f = new Form();
f.ShowDialog();

but this obviously loads/displays a blank form and not the form I defined in the form designer.

In my main application, I want to be able to show the login form programmatically, but when I try to use;

frmLogin.ShowDialog();

it tells me that "An object reference is required for the non-static field, method or property 'System.Windows.Forms.Form.ShowDialog()'

In the old days, I could show a form by simply using the above snippet of code. So, obviously something has changed since the last time I wrote a windows console app.

Can someone show me the error of my ways?

like image 619
Skittles Avatar asked Dec 05 '22 08:12

Skittles


2 Answers

This creates a new instance of type Form:

Form f = new Form();

Which, of course, is a blank form. It would appear that your type is called frmLogin. Normally this sounds like a variable name and not a class name, but the error you're getting here tells me that it's a class:

frmLogin.ShowDialog();

Given that, then the quickest way to solve your problem would be to create an instance of your form and show it:

frmLogin login = new frmLogin();
login.ShowDialog();

However, in keeping with naming standards and conventions (to help prevent future confusion and problems), I highly recommend renaming the form itself to something like:

LoginForm

Then you can use something like frmLogin as the variable name, which is a much more common approach:

LoginForm frmLogin = new LoginForm();
frmLogin.ShowDialog();
like image 79
David Avatar answered Dec 24 '22 18:12

David


The problem is that with the code snippet you took from Microsoft, you were just building the base Type. You need to build your form. So instead of new Form, you build a new frmLogin:

var f = new frmLogin();
f.ShowDialog();
like image 36
Mike Perrenoud Avatar answered Dec 24 '22 19:12

Mike Perrenoud