Question

i want to change password manually and send password to my users but i got the "Object reference not set to an instance of an object." error. what is wrong with my cods: thank you:

        Random r = new Random();
        string code = r.Next(100000, 9999999).ToString();

        //////////////////////////////////////////////////////////////////////////////////////////////

        string connStr = ConfigurationManager.ConnectionStrings["****"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(connStr);
        SqlCommand sqlcmd = new SqlCommand();
        sqlcmd = new SqlCommand("SELECT Count(ID) FROM RolInfo where username=@username", sqlconn);
        sqlcmd.Parameters.AddWithValue("@username", TextBox1.Text);

        sqlconn.Open();
        int count = ((int)sqlcmd.ExecuteScalar());


        sqlconn.Close();


        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        if (count != 0)
        {

          Sendmail();

            MembershipUser u = Membership.GetUser();
            u.ChangePassword(u.ResetPassword(), code);
        }
        else
        {
            lab_Message.Visible = true;
            lab_Message.Text = "This username is invalid.";
            lab_Message.ForeColor = System.Drawing.Color.Red;

        }

    }
    else
    {
        lab_Message.Visible = true;
        lab_Message.Text = "Please enter your username.";
        lab_Message.ForeColor = System.Drawing.Color.Red;
    }
    }
Was it helpful?

Solution

You're not passing in an argument to Membership.GetUser();

Membership.GetUser(); Gets the currently-logged in user. As you're not logged in it will return null. If you were logged in it would return only you, and not your members.

If you want to get the user then you need to pass in their username. Like this:

MembershipUser u = Membership.GetUser(TextBox1.Text);

UPDATE

You don't need to do a call to the SQL Database to check if the user exists.

you can do this instead.

   MembershipUser u = Membership.GetUser(TextBox1.Text);

   if (u != null){
      SendMail();
      u.ChangePassword(u.ResetPassword(), code);
   }else{
      lab_Message.Visible = true;
      lab_Message.Text = "This username is invalid.";
      lab_Message.ForeColor = System.Drawing.Color.Red;
   }

By the way, the users password will NOT be set to code - this will get set to the users answer to their security question. ResetPassword resets the password to an automatically generated one.

See here for documentation. http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser.resetpassword.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top