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;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
//获取CustomValidator控件绑定文本框的值
string userName=args.Value;
//连接数据库
SqlConnection con = new SqlConnection("server=.;database=Vote;uid=sa;pwd=;");
con.Open();
//查询所有符合条件的记录数
SqlCommand cmd = new SqlCommand("select count(*) from VoteDetails where VoteItem='" + userName + "'", con);
//返回查询条件的首行首列
int count =Convert.ToInt32( cmd.ExecuteScalar());
//如果没有找到
if (count == 0)
{
//则通过验证,不显示CustomValidator控件的错误信息
args.IsValid = true;
}
else
{
//否则不能通过验证,显示错误信息,用户以存在
args.IsValid = false;
}
//记住关闭数据库
//除了CustomValidator是服务器验证控件,其他的基本上多是客户端验证控件
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
//页面的全部数据有效则执行下列代码
if (this.IsValid)
{
Response.Write("提交");
}
else
{
Response.Write("页面无效");
}
}
}
浙公网安备 33010602011771号