我有一个表单我只想检查该用户是否已经存在,如果没有那么它保存在数据库中其他显示错误消息用户已经存在知道这个问题我问了很多次但我没找到我的解决方案 这是我的aspx代码:
protected void btnSubmit_Click(object sender, EventArgs e)
{
con.Open();
string FirstName = tbFirstName.Text;
string LastName = tbLastName.Text;
string Email = tbEmail.Text;
string Pass = tbPass.Text;
string ConfirmPass = tbConfirmPass.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Insert into UserDetails(@FirstName,@LastName,@Email,@Pass,@ConfirmPass)values('" + tbFirstName.Text + "','" + tbLastName.Text + "','" + tbEmail.Text + "','" + tbPass.Text + "','" + tbConfirmPass.Text + "')";
cmd.Parameters.AddWithValue("@FirstName", tbFirstName.Text.Trim());
cmd.Parameters.AddWithValue("@LastName", tbLastName.Text.Trim());
cmd.Parameters.AddWithValue("@Email", tbEmail.Text.Trim());
cmd.Parameters.AddWithValue("@Pass", tbPass.Text.Trim());
cmd.Parameters.AddWithValue("@ConfirmPass", tbConfirmPass.Text.Trim());
}
con.Close();
tbFirstName.Text = "";
tbLastName.Text = "";
tbEmail.Text = "";
tbPass.Text = "";
tbConfirmPass.Text = "";
tbFirstName.Focus();
}
在这个点击事件的按钮用户只能创建,但我想验证它是否存在于数据库中
答案 0 :(得分:1)
试试这段代码,它可能对您有所帮助。在您的点击事件中调用此函数。
public void CheckUser()
{
string strconn = @"Data Source=appserver3;Initial Catalog=Bart;User ID=bart1;Password=bart@12345";
SqlDataReader reader = null;
SqlConnection conn = null;
conn = new SqlConnection(strconn);
conn.Open();
DateTime Dt_Time = DateTime.Now;
string FirstName = tbFirstName.Text;
SqlCommand cmd = new SqlCommand("select FirstName from UserDetails where @FirstName='" + tbFirstName.Text + "'", conn);
cmd.Parameters.AddWithValue("@FirstName", tbFirstName.Text.Trim());
reader = cmd.ExecuteReader();
if (reader != null && reader.HasRows)
{
Response.Write("<script>alert('User Already Exist');</script>");
}
else
{
string strquery = string.Format("insert into UserDetails values('{0}')", @FirstName);
cmd = new SqlCommand(strquery, conn);
int count = (int)cmd.ExecuteNonQuery();
Response.Write("FirstName:" + FirstName);
}
}