Code behind problems

  • Thread starter Thread starter jlucas
  • Start date Start date
J

jlucas

Hello,

I am new to .Net and I need some help getting access to the controls in my
aspx code. It seems my cs class can not get a good reference to the
controls declared in my aspx file. Here are some code snippets that I have.

CreateUser.aspx
<%@ Page Inherits="CreateUser" Language="C#" Debug="true" %>
.....
<td width=80> <asp:TextBox id="First_Name" type="text" size="15"
runat="server"/></td>

CreateUser.cs
public class CreateUser:Page
{
protected System.Web.UI.WebControls.TextBox fName;
.......

fName = (TextBox)this.Page.FindControl("First_Name");
//
Console.WriteLine ("Enter the SaveUser Method! " +
fName.Text); //Exception thrown here.

So I have the cs class inherit from Page and then the aspx inherits the
CreateUser class. I have also made the reference in the CreateUser to
TextBox protected (and I have tried public), but I always get this error
"System.NullReferenceException: Object reference not set to an instance of
an object." which goes back to my TextBox control I am trying to use.

I have tried this as Page.FindControl("form1").findControl("First_Name")
and still get the same result.

Thanks for the help,

jlucas
 
instead of
protected System.Web.UI.WebControls.TextBox fName;
use
protected System.Web.UI.WebControls.TextBox First_Name;
since that's the ID assigned to it.
 
Curt,

I had that before, but when trying to use the FindControl I switched the
name and I did not think to put it back.

I got it to work, but I am not sure why. I did what you said but at the
same time I pulled my button_click method out of the aspx file and put it in
the cs file with the class. So my new question is, do you have to have all
of the code in the cs file for the code behind to work? I was thinking that
the method the button was tied to should be in the aspx file.

Thanks for your help,

jlucas
 
Back
Top