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