我正在使用 C# 在 asp.net 中构建一个 Web 应用程序。我有用户应该注册然后可以登录的表单。我在让网络应用程序知道用户选择的名称是“已经存在”或不存在时遇到问题。如果它已经存在,则不应插入相同的名称并显示一条消息“用户名已存在”。我试过了,SqlDataReader
但没有运气。
protected void Register_Button_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BJ_Player_String"].ToString());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlDataReader data_reader;
String name = TextBox2.Text;
String date = TextBox3.Text;
try
{
conn.Open();
cmd = new SqlCommand("Insert into BJ_Player (Player_Name, D_O_B) Values (@Player_name, @D_O_B)", conn);
cmd = new SqlCommand("Select Player_Name from BJ_Player WHERE Player_Name = @Player_name", conn);
cmd.Parameters.Add("@Player_name", SqlDbType.NVarChar).Value = name;
cmd.Parameters.Add("@D_O_B", SqlDbType.Date).Value = date;
cmd.Connection = conn;
data_reader = cmd.ExecuteReader();
cmd.ExecuteNonQuery();
if (data_reader.HasRows)
{
lblPlayerNameExists.Visible = true;
}
else
{
// do nothing
}
}