Sign in to follow this  
Hartley

[C#] WinForms problem, Object Reference not set?

Recommended Posts

I'm getting an error. I made a method inside Form1.cs called public static void InitVars() and inside is a piece of code attackButton = txtAttack.Text; (attackButton is a string) not on txtAttack.Text I get the error message, object reference not set to an instance of an object. I designed the layout in C#'s form designer thingy... Whats wrong? =(

Share this post


Link to post
Share on other sites
Remove 'static' and make sure you do not call InitVars before the Form.Load has been fired.

removing the static makes sure that this has a value and calling InitVars after the load makes sure that all controls have been initialized.

Share this post


Link to post
Share on other sites
txtAttack is null, so you get the null reference exception. Without more code, it's hard to say for sure why it's null. In general, post all code so we can provide better answers. But as ernow says, most likely you're trying to access a control that has not yet been created due to timing issues.

Share this post


Link to post
Share on other sites
Why are you doing this; "public static void InitVars()"? Unless they are static members it makes no sense.

If you have static members, then use the static Constructor, if not then you should not be using static.

The problem is that your txtAttack may not even exist, and may not be accessible depending on the situation.

theTroll

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this