无刷新检查用户名是否可以注册

来源:互联网 发布:软件开发专业怎么样 编辑:程序博客网 时间:2024/04/27 22:52

 <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
         <ContentTemplate>
            用户名: <asp:TextBox ID="tbUserName" runat="server"></asp:TextBox><asp:RequiredFieldValidator
                ID="RequiredFieldValidator1" runat="server" ErrorMessage="不能为空"
                 ControlToValidate="tbUserName" Display="Dynamic"></asp:RequiredFieldValidator>
             <br />
             <asp:Button ID="btnCheckName" runat="server" CausesValidation="False"
                 onclick="btnCheckName_Click" Text="检测我的用户名?" />
             <br />
             <asp:Label ID="lblMsg" runat="server" Text="Label"></asp:Label>
         </ContentTemplate>
        </asp:UpdatePanel>

 

 

 protected void btnCheckName_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(tbUserName.ToString()))
        {
            lblMsg.Text = "请输入名称。";
            lblMsg.ForeColor = System.Drawing.Color.Red;
            return;
        }
        if (CheckUserNameIsExist(tbUserName.Text) > 0)
        {
            lblMsg.Text = "非常遗憾,您的用户名已注册。";
            lblMsg.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblMsg.Text = "恭喜您,此用户名可以注册!";
            lblMsg.ForeColor = System.Drawing.Color.Green;
        }
    }
    private int CheckUserNameIsExist(string username)
    {
        using (SqlConnection myCon = new SqlConnection(ConfigurationManager.ConnectionStrings["CMSDBConnectionString"].ConnectionString))
        {
            string cmdText = "select count(*) as usercount from [User] where UserName='"+ username +"'";
            using (SqlCommand cmd = new SqlCommand(cmdText, myCon))
            {
                SqlDataReader dr = null;
                int userCount = 0;
                if (myCon.State == ConnectionState.Closed)
                    myCon.Open();
                try
                {
                    dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    if (dr == null)
                        return -1;

                    if (dr.Read())
                    {
                        userCount = Int32.Parse(dr["usercount"].ToString());
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    dr.Close();
                    myCon.Close();
                }
                return userCount;
            }
        }
    }

原创粉丝点击