您的位置:首页 > 编程语言 > ASP

ASP.NET 文本框失去焦点事件验证用户是否已经存在

2012-10-10 22:44 555 查看
新建一个网站,在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;
    }
  }
}

最后上图:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: