[网络收集]AJAX 验证用户名是否存在,使用UpdatePanel

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Index.aspx.cs" Inherits="Index" %>

<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken

=31bf3856ad364e35" 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>


 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class 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);
        }


 

摘自http://www.cnblogs.com/lavenderzh/archive/2009/05/23/1487588.html

原文地址:https://www.cnblogs.com/lushuicongsheng/p/1891909.html