• Advertisement
Sign in to follow this  

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

This topic is 3183 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement