C# ASP.NET Webforms: TextBox(Not Textbox.Text) is coming out null. How do you fix this?

0

I am testing out a webform to save strings from a textbox. The program stops running when I press a button programmed to save the info into an array. Here's the error:

System.NullReferenceException occurred HResult=0x80004003 Message=Object reference not set to an instance of an object. Source=TS_Webform StackTrace: at TS_Webform.Forms.Login.registerUser() in C:\Users\k20\Source\Repos\TS_Webform\TS_Webform\Forms\Login.aspx.cs:line 105 at TS_Webform.Forms.Register2.Button1_Click(Object sender, EventArgs e) in C:\Users\k20\Source\Repos\TS_Webform\TS_Webform\Forms\Register2.aspx.cs:line 25

heres the method that it the message directs me to:

   public static void registerUser()
   {
        User newUser = new User();
        Register2 register2 = new Register2();
        newUser.strName = register2.TextBox1.Text;//Stops here 
        newUser.strPW = register2.TextBox2.Text;
        //newUser.strEmail = textBox3.Text;
        newUser.strPhone = register2.TextBox3.Text;
        newUser.strHas = register2.TextBox4.Text;
        newUser.strNeeds = register2.TextBox5.Text;
        userArray[I(userArray)] = newUser;
   }

I tried numerous things like changing the Textbox-declaration line on Register2.aspx.designer.cs from protected to public and public static and neither has worked.

c#
asp.net
nullpointerexception
webforms
textbox
asked on Stack Overflow Aug 2, 2017 by Kevin Serrano • edited Aug 2, 2017 by Koby Douek

2 Answers

0

This sort of thing can happen when your code behind gets out of sync with your web form markup. For every control that is in your markup, there is supposed to be a protected member in the code behind class; if they do not match up properly, you can get an orphaned control, or the member can return null.

The simplest way to fix this is to completely delete the control (from both markup and code behind) and add it again using the form designer.

answered on Stack Overflow Aug 2, 2017 by John Wu
0

I fixed the problem. The method, registerUser(), is on a different page, Login.aspx.cs. I moved that method to Register2.aspx.cs. For whatever reason when the button on Register2 calls the method from Login.aspx.cs it resets the textboxes to null or the method isn't really responding to the fact that Register2 is open/loaded.

answered on Stack Overflow Aug 2, 2017 by Kevin Serrano

User contributions licensed under CC BY-SA 3.0