注册用户时,用户名为什么只能输入数字?
protected void btnRegister_Click(object sender, EventArgs e)
{
conn.Open();
string strsql = "select count(*) from Users where UserName=" + this.TextBox1.Text.Trim();
SqlCommand cmd = new SqlCommand(strsql, conn);
//string s = cmd.ExecuteScalar();
int i = Convert.ToInt32(cmd.ExecuteScalar());
if (i == 0)
{
string sql = "insert into Users values('" + this.TextBox1.Text + "','" + this.TextBox2.Text + "')";
if (this.TextBox1.Text != "" && this.TextBox2.Text != "")
{
SqlCommand cmd2 = new SqlCommand(sql, conn);
cmd2.ExecuteNonQuery();
Response.Redirect("login.aspx");
}
else
{
Response.Write("<script>alert('用户名或密码不能为空!')</script>");
}
}
else
{
Response.Write("<script>alert('姓名冲突,请重新输入!')</script>");
this.TextBox1.Text = "";
this.TextBox1.Focus();
}
}
数据库中的用户表Users,字段用户名UserName是char类型,输入字符或汉字时, “int i = Convert.ToInt32(cmd.ExecuteScalar());”这行代码出错:列名 '张三' 无效。。不知道什么原因,请高手指教一下!
[解决办法]
cmd.ExecuteScalar 获取第一行第一列值与用户名无关
字符串类型
string strsql = "select count(*) from Users where UserName='" + this.TextBox1.Text.Trim()+"'";使用nvarchar类型