我試圖插入和更新數據使用相同的按鈕。我創建了方法(uniqueEmail())來檢查表中是否存在電子郵件地址。如果電子郵件沒有預設,使用這種方法我試圖插入數據。 這裏是我的代碼,請糾正我在哪裏出錯。插入和更新函數工作在單擊按鈕在C#
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=register;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
if (uniqueEmail()==true)
{
cmd.CommandText = "update registeruser set email='" + TextBox1.Text + "', password='" + TextBox2.Text + "' where email='" + TextBox1.Text + "'";
}
else
{
cmd.CommandText = "insert into registeruser values('" + TextBox1.Text + "', '" + TextBox2.Text + "')";
}
cmd.ExecuteNonQuery();
con.Close();
}
public bool uniqueEmail()
{
string stremail;
string querye = "select count(email) as email from registeruser";
SqlCommand cmd = new SqlCommand(querye, con);
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
try
{
stremail = dr["email"].ToString();
return(stremail != "0");
if (stremail != "0")
{
//errlblemail.Text = "email already exist";
return false;
}
}
catch (Exception e)
{
string message = "error";
message += e.Message;
}
finally
{
dr.Close();
}
}
return true;
}
}
代碼看起來不錯,現在是什麼問題? –
@nirmala你的代碼很好。請寫出什麼是錯誤? –
如果我使用現有的emailid進行註冊,而不是更新數據,則會再插入一次。 – Nirmala