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

Started by
2 comments, last by TheTroll 14 years, 10 months ago
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? =(
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.
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.
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

This topic is closed to new replies.

Advertisement