2012-02-24 40 views
0

我正在尝试将用户登录详细信息写入数据库。 当我点击提交按钮我得到一个NullReferenceException。 有4个文本框 用户名,电子邮件,密码和ConfirmPassword。ASP.NET NullReferenceException

protected void Button1_Click(object sender, EventArgs e) 
     { 
      if ((RegisterUserWizardStep.FindControl("Password") as TextBox).Text == (RegisterUserWizardStep.FindControl("ConfirmPassword") as TextBox).Text) 
      { 
       //call the method to execute insert to the database 
       ExecuteInsert((RegisterUserWizardStep.FindControl("UserName") as TextBox).Text, 
           (RegisterUserWizardStep.FindControl("Email") as TextBox).Text, 
          (RegisterUserWizardStep.FindControl("Password") as TextBox).Text); 
       Response.Write("Record was successfully added!"); 
       ClearControls(Page); 
      } 
      else 
      { 
       Response.Write("Password did not match"); 
       (RegisterUserWizardStep.FindControl("Password") as TextBox).Focus(); 
      } 
     } 

谢谢。

+1

哪条线发生异常? – 2012-02-24 12:09:21

+0

而当你打破它正在使用的值为空的异常?回答这些问题,你几乎解决了你的问题。 ;-) – Chris 2012-02-24 12:11:01

+0

另外,只是为了检查。在你的描述中你说过你有一个'用户名'文本框。代码正在寻找'RegisterUserWizardStep.FindControl(“UserName”)'。这是一个错字吗? – 2012-02-24 12:11:13

回答

0

其可能的FindControl没有找到你后的控制,可能是因为该文本框是nested under another child control像面板等

而不是

if ((RegisterUserWizardStep.FindControl("Password") as TextBox).Text 

尝试

TextBox passwordTextBox = RegisterUserWizardStep.FindControl("Password") as TextBox; 
// .. same for username and email 
if ((passwordTextBox != null) && (usernameTextBox != null) ...) 
{ 
// Do something with the textboxes 
} 
// else you have a bug 

这也将阻止您在同一控件上重复FindControl代码(DRY原理)

+0

谢谢。有效..:) – android 2012-02-24 12:26:36

1

你提到有四个控件 - 用户名,电子邮件,密码和ConfirmPassword

你看到空的例外是几乎可以肯定,因为的FindControl(X)将返回空

检查的更好的方法是这样做:

TextBox myTextBox = RegisterUserWizardStep.FindControl(X) as TextBox; 

if(myTextBox != null){ 
    //Continue 
} 
else{ 
    //Write out some error information - now you know what the problem is. 
} 

而且,这是不相关的即时错误,但你喂每个文本框的内容,直接进入您的ExecuteInsert方法 - 你会更好做一些验证,也只是为了检查你是否有预期的价值。

0

类似的代码RegisterUserWizardStep.FindControl("UserName") as TextBox将返回null或者如果没有名为UserName控制或者叫UserName的控制不能转换为TextBox。这很可能是您的例外情况的来源,因为您试图获取可能为null的引用的属性Text

为了更好地理解问题的所在,你可以定义一个扩展功能:

static class ControlExtensions { 

    public T Find(this Control parent, String name) where T : Control { 
    var control = parent.FindControl(name); 
    if (control == null) 
     throw new ArgumentException(String.Format("Cannot find control named '{0}'.", name); 
    var t = control as T; 
    if (t == null) 
     throw new ArgumentException(String.Format("Control named '{0}' does not have type '{1}.", name, typeof(T).Name); 
    return t; 
    } 

} 

然后,您可以得到UserName控制的Text属性:

RegisterUserWizardStep.Find<TextBox>("UserName").Text 

此调用将抛出更多如果找不到控件,则为描述性异常。

0

在您的描述中,你已经说过你有一个Username文本框。

该代码正在查找RegisterUserWizardStep.FindControl("UserName")

这是问题中的拼写错误吗?否则它可能是异常的原因。

相关问题