C# 对象引用未设置为对象的实例。

C# 对象引用未设置为对象的实例。,c#,asp.net,asp.net-membership,C#,Asp.net,Asp.net Membership,我在createuserwizard中有一个附加步骤,完成表单后,它会将用户信息存储在数据库中。但是发生了以下错误: Source Error: Line 55: MembershipUser User = Membership.GetUser(UserNameTextBox.Text); Line 56: Line 57: Object UserGUID= User.ProviderUserKey; //error appe

我在createuserwizard中有一个附加步骤,完成表单后,它会将用户信息存储在数据库中。但是发生了以下错误:

Source Error: 

Line 55:                MembershipUser User = Membership.GetUser(UserNameTextBox.Text);
Line 56:   
Line 57:                Object UserGUID= User.ProviderUserKey; //error appeared here
Line 58:   
Line 59:                DataSource.InsertParameters.Add("UserId", UserGUID.ToString());
我还设置了一个断点链接55、57、59。从第57行开始,用户为null,他们无法从数据库中获取用户

代码隐藏:

Object reference not set to an instance of an object.

尽管此方法名为“CreateUserWizard1_CreatedUser”,但由于其签名,我可以看到它是用于CreatingUser事件的。在此事件期间,尚未创建用户。使用CreatedUser事件进行此操作。

表示指定用户的MembershipUser对象。如果 用户名参数与现有用户不对应,此 方法返回null

将用户对象选中为null,然后尝试访问该对象的属性。如果没有具有指定名称的用户,则此方法返回null。尝试将您的代码放到
onfinishButton单击
event,如果您无法从成员身份访问用户对象,希望这对您有用

protected void CreateUserWizard1_CreatedUser(object sender, System.Web.UI.WebControls.LoginCancelEventArgs e)
    {  
       MSCaptcha.CaptchaControl Captcha1 = (CreateUserWizardStep1.ContentTemplateContainer.FindControl("Captcha1") as MSCaptcha.CaptchaControl);

       TextBox txtCaptcha = (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("txtCaptcha");
       Label Captchalbl = (Label)CreateUserWizardStep1.ContentTemplateContainer.FindControl("Captchalbl");

       Response.Write(txtCaptcha.Text); 

           Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim()); 

           if (!Captcha1.UserValidated)
           {

                Captchalbl.Text = "InValid";

               e.Cancel = true;
           } 
            else
           {
               Captchalbl.Text = "Valid";

               TextBox UserNameTextBox =
              (TextBox)CreateUserWizardStep1.ContentTemplateContainer.FindControl("UserName");

               SqlDataSource DataSource =
                   (SqlDataSource)CreateUserWizardStep1.ContentTemplateContainer.FindControl("InsertExtraInfo");

               MembershipUser User = Membership.GetUser(UserNameTextBox.Text);

               Object UserGUID= User.ProviderUserKey; //here is link 57. 

               DataSource.InsertParameters.Add("UserId", UserGUID.ToString());

               DataSource.Insert();

            }
   }

Membership.GetUser()
使用内置提供程序还是自定义提供程序?如果是后者,则调试到其中以确定返回
null
的原因。如果是前者,请检查数据以查看请求的用户是否确实存在。(如果是前者,我会认为微软打破了良好的设计惯例,将
null
作为“魔法值”返回,而不是抛出异常或提供无法找到请求用户的明确指示,但我离题了……)您是否试过使用
CreateUserWizard
Membership.GetUser(CreateUserWizard1.UserName)
。您好。我已经尝试了你的方法,但仍然存在相同的错误。您好,如果我将Object UserGUID=User.ProviderUserKey放入If语句,则会出现另一个错误。似乎他们无法定义wad是UserGuid。。错误是:在当前上下文中找不到UserGuid意味着您必须放置其他代码,如果这取决于您用户的提供程序,那么这只是帮助您理解的示例。。编码快乐。嗨,非常感谢。你解决了我的问题。正如您所建议的,将Insert方法放置到CreatedUser事件中,而不是CreatingUser事件中
if( User != null)
{
  Object UserGUID= User.ProviderUserKey;
}