下面是我写的一段简单的注册表单只有用户名和密码;当然了是为了测试特意写的,先前就遇到这个问题,到网上查了N久都没有找到答案,希望大侠们帮我改正一下代码。
问题很明显,这段代码经过刷新之后会重新向数据库添加数据,意思就是说:点完提交不关闭页面,只要一刷新就导致了页面提交
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 Button1_Click(object sender, EventArgs e)
    {
        string strid = txtID.Text;
        string strpwd = txtPWD.Text;
        string strpwdAn = txtPWDAgain.Text;
        string strCon="Data Source=bk60538\\sqlexpress;Initial Catalog=userinfo;Integrated Security=True";
        SqlConnection con = new SqlConnection(strCon);
        string strCmd;
        SqlCommand cmd;
        try
        {
            con.Open();
            strCmd = "select count(*) from t_user where userid=@uid";
            cmd = new SqlCommand(strCmd, con);
            cmd.Parameters.AddWithValue("@uid", strid);
            int count =Convert.ToInt32(cmd.ExecuteScalar());
            if (count > 0)
            {
                Response.Write("用户名已经存在");
            }
            else
            {
                strCmd = "insert into t_user values(@userid,@userpwd)";
                cmd = new SqlCommand(strCmd, con);
                cmd.Parameters.AddWithValue("@userid", strid);
                cmd.Parameters.AddWithValue("@userpwd", strpwd);
                cmd.ExecuteNonQuery();
                Response.Write("写入成功");
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            cmd = null;
            con.Close();
            con = null;
        }
    }
}