Namespace="System.Web.UI" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>验证用户名是否存在</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
<asp:ScriptManager ID="ScriptManager1" runat="server">
        
</asp:ScriptManager>
    
    
</div>
        
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
            
<ContentTemplate>
                
<asp:TextBox ID="tb_username" runat="server" Width="85px" AutoPostBack="True" OnTextChanged="tb_username_TextChanged"></asp:TextBox>
                
<asp:Label ID="lb_info" runat="server" Width="76px"></asp:Label>
                
<asp:TextBox ID="tb_Pwd" runat="server" Width="85px" TextMode="Password"></asp:TextBox><br />
                
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                
<asp:Button ID="Button1" runat="server" Text="注册" OnClick="Button1_Click" />
            
</ContentTemplate>
        
</asp:UpdatePanel>
    
</form>
</body>
</html>

 Index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
if (!this.IsPostBack)
        {
            ScriptManager1.SetFocus(
"tb_username");
        }
    }
    
private bool CheckUser()
    {
        
int count = 0;
        SqlConnection conn 
= new SqlConnection("server=.;uid=sa;pwd='';database=UserInfo");
        
string username = this.tb_username.Text;
        
string strsql = "select count(uid) from userinfo where username='"+username+"'";
        SqlCommand cmd 
= new SqlCommand(strsql,conn);
        conn.Open();
        count 
= (int)cmd.ExecuteScalar();
        conn.Close();
        
if (count == 0)
        {
            
return true;
        }
        
else
        {
            
return false;
        }

    }


    
protected void Button1_Click(object sender, EventArgs e)
    {
        
if (!CheckUser())
        {
            
this.lb_info.Text = "用户名已经存在";
            ScriptManager.RegisterStartupScript(
this.UpdatePanel1, UpdatePanel1.GetType(), """document.getElementById('tb_username').select();"true);
        }

       else

       {
            lb_info.Text 
= "注册成功";

       }
    }
    
protected void tb_username_TextChanged(object sender, EventArgs e)
    {

       this.lb_info.Text="";
        
if (this.CheckUser())
        {
            
this.lb_info.Text = "用户名可以使用";
            ScriptManager1.SetFocus(
"tb_Pwd");
        }
        
else
        {
            
this.lb_info.Text = "用户名已经存在,请重新注册!";           
            
        }
    }
}

相关文章: