背景:VisualStudio2005;
             使用自定义控件判断注册用户名是否已经存在;
实现:
html:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomValidator.aspx.cs" Inherits="CustomValidator" %>
<!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>
        <table>
            <tr>
                <td style="width: 72px; height: 21px">
                    用户名:</td>
                <td style="width: 90px; height: 21px">
                    <asp:TextBox ID="txtName" runat="server" Width="86px"></asp:TextBox></td>
                <td style="width: 163px; height: 21px">
                    <asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="txtName"
                        ErrorMessage="用户已经存在!" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator></td>
            </tr>
        </table>
   
    </div>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </form>
</body>
</html>
code:
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 CustomValidator : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
       //取得要在CustomeValidator.ServerValidate事件的自定义事件处理程序中验证的值
        string userName = args.Value;
        SqlConnection con = DB2.createCon();
        con.Open();
        //查询该用户名记录集
        SqlCommand cmd = new SqlCommand("select count(*) from tb_user where userName='" + userName + "'", con);
        int count = Convert.ToInt32(cmd.ExecuteScalar());
        //如果count>0表明在数据库中已经存在该用户名,且设置args.IsValid属性为false,表示未通过验证
        if (count > 0)
        {
            //获取或设置由 ServerValidateEventArgs.Value属性指定的值是否通过验证
            args.IsValid = false;
        }
        else
        {
            args.IsValid = true;
        }

    }
}
DB2.cs
using System;
using System.Data;
using System.Configuration;
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;
/// <summary>
/// DB2 的摘要说明
/// </summary>
public class DB2
{
 public DB2()
 {
  //
  // TODO: 在此处添加构造函数逻辑
  //
 }
    public static SqlConnection createCon()
    {
        return new SqlConnection("server=localhost\\sqlexpress;database=db_login;uid=sa;pwd=hello");
    }
}
 
注:可以使用Page.IsValid属性指示页验证是否成功