添加到数据库时,对象引用未设置为对象的实例

时间:2014-07-01 16:05:06

标签: c# asp.net webforms

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=PIYUSH-PC\\SQLEXPRESS;Initial Catalog=piyush;Integrated Security=True");
    SqlCommand cmd = new SqlCommand("SPRegisterUser", con);

    cmd.CommandType = CommandType.StoredProcedure;

    SqlParameter username = new SqlParameter("@Username_V", TextBox1.Text);
    SqlParameter email = new SqlParameter("@Email_V", TextBox2.Text);
    SqlParameter password = new SqlParameter("Password_V", TextBox3.Text);

    cmd.Parameters.Add(username);
    cmd.Parameters.Add(password);
    cmd.Parameters.Add(email);
    try
    {
        con.Open();
        int ReturnCode = (int)cmd.ExecuteScalar();
        if (ReturnCode == -1)
        {
            Response.Write("Username already exists");
        }
        else
        {
            Response.Redirect("WebForm2.aspx");
        }
    }
    catch (Exception e1)
    {
        Response.Write(e1);
    }
    finally
    {
        con.Close();
    }
}

以上代码运行但显示以下内容 - System.NullReferenceException:未将对象引用设置为对象的实例。 at eGaffar_23_6_2014_.WebForm1.Button1_Click(Object sender,EventArgs e)

1 个答案:

答案 0 :(得分:0)

你的第3个参数必须是@Password_V,因为在传递值的参数时你需要添加@也是