对象引用未设置为asp.net的对象实例

时间:2014-01-07 07:09:58

标签: c# asp.net

    protected void Page_Load(object sender, EventArgs e)
    {
        lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;

        string sql = "Select password from Profile where userid = '" + Session["userid"] + "'";
        SqlCommand cmd = new SqlCommand();
        SqlDataReader dr; // to hold reference of datareader  returned

        //prepare  a place - datatable to hold the data
        DataTable dt = new DataTable();

        //setting up command
        cmd.CommandText = sql;
        cmd.Connection = con;

        //connection and execute command
        con.Open();
        dr = cmd.ExecuteReader();

        dt.Load(dr); // copy data from datareader to datatable

        string pwdcheck;
        pwdcheck = dt.Rows[0]["password"].ToString();

        if (tb_verify.Text.Equals(pwdcheck))
        {
            string password = tb_pwd.Text;

            sql = "Update Profile set password ='" + password + "'";
            sql = sql + "where userid = '" + Session["userid"] + "'";

            cmd.CommandText = sql;
            cmd.Connection = con;

            try
            {
                cmd.ExecuteNonQuery();
                lb_msg.Text = "Password changed succesfully";
            }
            catch (Exception ex)
            {
                lb_msg.Text = "Problems encountered " + ex.Message;
            }


            finally
            {
                con.Close();
                con.Dispose();
                cmd.Dispose();
            }
        }
        else
            lb_msg.Text = "Old password Incorrect";
    }

    protected void lblClick(object sender, EventArgs e)
    {
        FormsAuthentication.SignOut();
        Session.Clear();  // This may not be needed -- but can't hurt
        Session.Abandon();
        FormsAuthentication.RedirectToLoginPage();
    }
}

lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";

上面一行有错误 Object reference not set to an instance of an object更改密码功能之前正在运行。

1 个答案:

答案 0 :(得分:1)

在您的情况下,Session["userid"]必须为NULL,请处理