我的意图时不能有相同的用户名和邮箱。
但我感觉写的蛮复杂的。。有哪里可以简化一下吗?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 UserRegisterValidate : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("用户名为:" + TextBox1.Text + "<br/>");
        Response.Write("密码为:" + TextBox2.Text + "<br/>");
        Response.Write("年龄为:" + TextBox4.Text + "<br/>");
        Response.Write("邮箱为:" + TextBox5.Text + "<br/>");        {
            SqlConnection sqlcon = new SqlConnection("Data Source=(local);DataBase=user;User ID=sa;PWD=yangguo");
            sqlcon.Open();
            SqlCommand Cmdc = new SqlCommand("select count(*) from id where name='" + TextBox1.Text + "'", sqlcon);
            int count = Convert.ToInt32(Cmdc.ExecuteScalar()); 
            if (count > 0)
            {
                Response.Write("<script>alert('该用户名已经存在');location='javascript:history.go(-1)'</script>");
            }      
        }
        {
            SqlConnection sqlcon = new SqlConnection("Data Source=(local);DataBase=user;User ID=sa;PWD=yangguo");
            sqlcon.Open();
            SqlCommand Cmdc = new SqlCommand("select count(*) from id where email='" + TextBox5.Text + "'", sqlcon);            int count = Convert.ToInt32(Cmdc.ExecuteScalar());             if (count > 0)
            {
                Response.Write("<script>alert('该邮箱已经存在');location='javascript:history.go(-1)'</script>");
            }            else
            {
                SqlConnection sqlconn = new SqlConnection("Data Source=(local);DataBase=user;User ID=sa;PWD=yangguo");
                sqlconn.Open();
                SqlCommand Cmd = new SqlCommand();
                Cmd.Connection = sqlconn;
                Cmd.CommandText = "Insert into id([name],[password],[age],[email]) values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox4.Text + "','" +
                TextBox5.Text + "')";
                Cmd.ExecuteNonQuery();
                sqlconn.Close();
                Response.Redirect("~/index.htm");
            }
        }
    }       
      
    

解决方案 »

  1.   

    不用这样把,你可以用 .net 的成员管理啊,很好用,还可以配置自己的实现方法
      

  2.   

    你是要简化代码么?
    代码的确是可以简化的,
    比如上面的建立连接,你完全可以把它写成一个公共类,还有查询用户名是否重复,邮箱是否重复,写成一个公司用类就可以了。给你一些提示吧:
    public int mydata()
    {
       //这里假设你的数据库连接conn和command已经存在了
       int i=Convert.ToInt32(cmd.ExecuteScalar());
       return i;
    }
    还有,像你那样直接向数据库中插入数据是不行的,最好用参数的形式
      

  3.   

    连接数据库的的代码,可以存放到一个SqlHelper类里面,
    每次使用调用就可以了