2015-04-14 56 views
-4

當我填寫表格,然後點擊註冊,它顯示了一個錯誤:錯誤這段代碼

Object reference not set to an instance of an object.

的錯誤是在這裏:

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

哪些對象必須添加到refrence?

這裏是網頁的代碼:

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()); 
     } 
    } 
} 

回答

3

從您發佈錯誤消息,很明顯的是,com.ExecuteScalar()爲空。因此,當你調用ToString方法時,你會得到一個空引用異常。由於com.ExecuteScalar()可以爲空,所以我建議你檢查一下。

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

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