Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Add Function to Form Class

Status
Not open for further replies.

jayplus707

Programmer
Jul 29, 2002
17
0
0
US
I'm new at C# and I can't figure this out. I have two forms. One is called frmTitle. The other is called frmPasswords. My main is in frmTitle. I created a function called doThis() inside my frmTitle class. I used the following code:

public void doThis() {}

And within my main, it starts like this:
Application.Run(new frmTitle());

Right afterwards, I want to put:
frmTitle.doThis();

But I get a reference error (An object reference is required for the nonstatic field, method, or property)! I know it's probably something stupid I overlooked, so can someone help me? I've tried just doing frmTitle. to see what members/functions come up, and my doThis function doesn't come up. Why not? I even tried doing it from my other form and it still doesn't come up....=\
 
When you said "new frmTitle()", it created an instance behind the scene for you. And then... it went out of scope because you didn't assign it to a variable. So by the time you go to call your doThis() method, there's no instance for it to work with. Try this:

Form MyForm = new frmTitle();
Application.Run(MyForm);
MyForm.doThis();

But I suspect what you really want to do is put your code that's in your doThis() method into the form's constructor (the method that VS.NET put in there for you when you created the form). BTW, make sure it's after the call to the WinForm initialize stuff.

Chip H.
 
Yes, Chip is right. You probably want to do it in the constructor or elsewhere in the class frmTitle.

Once you have the statement:

Application.Run(new frmTitle());

you are operating in an instance of the frmTitle class. So if you want to modify the frmTitle window, for example, you can put this in the constructor or in a button event handler:

public class frmTitle : System.Windows.Forms.Form
{
public frmTitle()
{
InitializeComponents();

this.Width = this.Width*2;
}
private void btnTest_Click(object sender, System.EventArgs e)
{
this.doThis();
}

}

this is pretty much equivalent to:

Form MyForm = new frmTitle();
MyForm.Width *= 2;
Application.Run(MyForm);



Dean
---
goddette@san.rr.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top