在按提交按钮

时间:2015-07-20 16:54:10

标签: c# ms-access insert insert-update

我有这个代码隐藏:

protected void cmdSave_Click(object sender, EventArgs e)
{

    string sFilePath = Server.MapPath("Database3.accdb");
    OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
    using (Conn)
    {
        Conn.Open();
        OleDbCommand myCommand = new OleDbCommand("SELECT COUNT(*) FROM colaborador WHERE username=@username", Conn);
        myCommand.Parameters.Add("?", OleDbType.VarChar).Value = HttpContext.Current.User.Identity.Name;
        int totalRegistos = (int)myCommand.ExecuteScalar();
        if (totalRegistos > 0)
        {
            //      user already answered
            lblInfo0.Text = "The user already asnwered";
        }
        else
        {
            //      the user didn't asnwered

            string insertCmd = "INSERT INTO colaborador(Empresa,Empresa2,Telemovel,username) VALUES (@Empresa,@Empresa2,@Telemovel,@username)";
               // insere na tabela colaborador os campos empresa, empres2, user os valores @ 
            {
                OleDbCommand myCommand2 = new OleDbCommand(insertCmd, Conn);
                myCommand2.Parameters.AddWithValue("@Empresa", empresa.Text);
                myCommand2.Parameters.AddWithValue("@Empresa2", empresa2.Text);
                myCommand2.Parameters.AddWithValue("@Telemovel", telemovel.Text);
                myCommand2.Parameters.AddWithValue("@username", HttpContext.Current.User.Identity.Name);
                Response.Write(myCommand.ExecuteNonQuery());
                lblInfo.Text = "Data saved!";
                lblInfo.ForeColor = System.Drawing.Color.Green;
            }
        }
    }
}   

这个工作正常没有错误并且如果用户名存在则保存到数据库中说出消息"用户已经回答"

然而我需要按提交按钮。

有没有办法说明消息(如果用户名已经存在)之前字段text.box?我怎样才能改变我的代码呢?

1 个答案:

答案 0 :(得分:0)

if (!IsPostBack)
{
    string sFilePath = Server.MapPath("Database3.accdb");
    OleDbConnection Conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sFilePath + ";Persist Security Info=False;");
    using (Conn)
    {
        Conn.Open();
        OleDbCommand myCommand = new OleDbCommand("SELECT COUNT(*) FROM colaborador WHERE username=@username", Conn);
        myCommand.Parameters.Add("?", OleDbType.VarChar).Value = HttpContext.Current.User.Identity.Name;
        int totalRegistos = (int)myCommand.ExecuteScalar();
        if (totalRegistos > 0)
        {
                // Já registado
                lblInfo0.Text = "O username já existe na base de dados";

                empresa.Enabled = false;
                empresa2.Enabled = false;
                telemovel.Enabled = false;
                cmdSave.Visible = false;
        }
    }
}