此代码出错

时间:2015-04-14 22:10:17

标签: c# asp.net

当我填写表单并单击注册时,它会显示错误:

  

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

错误在于:

int temp=Convert.ToInt32(com.ExecuteScalar().ToString());

必须在参考中添加哪个对象?

以下是网页的代码:

public partial class register : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.DataBind();
        if(IsPostBack)
        {
            SqlConnection conn = new 
                SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
                tring"].ConnectionString);
            conn.Open();
            string checkuser = "SELECT * FROM [Table] where user_name ='" + 
                Text_username + "'";
            SqlCommand com = new SqlCommand (checkuser , conn);
            int temp=Convert.ToInt32(com.ExecuteScalar().ToString());
            if (temp == 1){
                Response.Write("User already exists");
            }
            conn.Close();
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Text_fname.Text = "";
        Text_lname.Text = "";
        Text_email.Text = "";
        Text_password.Text = "";
        Text_password_again.Text = "";
        Text_username.Text = "";
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        { 
            SqlConnection conn = new 
                SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionS
                tring"].ConnectionString);
            conn.Open();
            string insert = "insert into Table 
                (user_fname,user_lname,user_email,user_password,user_name) values (@firstName 
                ,@lastName ,@Email ,@passWord ,@userName)";
            SqlCommand com = new SqlCommand (insert , conn);
            com.Parameters.AddWithValue("@firstName", Text_fname.Text);
            com.Parameters.AddWithValue("@lastName", Text_lname.Text);
            com.Parameters.AddWithValue("@Email", Text_email.Text);
            com.Parameters.AddWithValue("@passWord", Text_password.Text);
            com.Parameters.AddWithValue("@userName", Text_username.Text);
            com.ExecuteNonQuery();
            Response.Write("Registration is successful");
            Response.Redirect("Default.aspx");
            conn.Close();
        }
        catch (Exception ex)
        {
            Response.Write("Error: " + ex.ToString());
        }
    }
}

1 个答案:

答案 0 :(得分:3)

从您发布的错误消息中可以清楚地看出com.ExecuteScalar()为空。因此,当您在其上调用ToString方法时,您将获得空引用异常。由于com.ExecuteScalar()可以为null,我建议您检查一下。

int temp;
var result = com.ExecuteScalar();
if(result != null)
{
    temp = Convert.ToInt32(result.ToString());
}

if (temp == 1)
{
    Response.Write("User already exists");
}