新建一个网站,在web.config中添加代码:
<connectionStrings>
<add name="SqlConn" connectionString="server=.;database=Test;uid=sa;pwd=123"/> </connectionStrings>
然后Default.aspx代码:
<body>
<form id="form1" runat="server"> <div> 用户名:<asp:TextBox ID="txtUserName" runat="server" ontextchanged="txtUserName_TextChanged" AutoPostBack="true" ></asp:TextBox>
<asp:Label ID="lblMessage" runat="server" Text="用户名不能为空!" Font-Size="Small" ForeColor="Red"></asp:Label>
<br /> 密码:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="密码长度6,由字符、数字、组成" Font-Size="Small" ForeColor="Red"></asp:Label> </div> </form></body>接着是Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{ protected void Page_Load(object sender, EventArgs e) { } protected void txtUserName_TextChanged(object sender, EventArgs e) { bool result = CheckUserName(txtUserName.Text.Trim()); if (result == true) { lblMessage.Text = "恭喜您,此用户名可以使用!"; } if (result == false) { lblMessage.Text = "该用户名已存在,请更换用户名!"; } } public static bool CheckUserName(string username) { string connectionString = ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString; SqlConnection conn = new SqlConnection(connectionString); conn.Open(); string sql = "select * from T_User where UserName = '" + username +"'"; SqlCommand cmd = new SqlCommand(sql, conn); try { int count = Convert.ToInt32(cmd.ExecuteScalar()); conn.Close(); if (count > 0) { return false; } else { return true; } } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } }}
最后上图: