在按下提交按钮之前检查用户名是否存在

Check if username exists before pressing submit button

我有这个代码隐藏:

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;
            }
        }
    }
}   

这工作正常,没有错误,如果用户名存在,也可以保存到数据库中,请留言 "user already answered"

但是我需要按提交按钮。

有什么方法可以说消息(如果用户名已经存在) 字段 text.box 之前?我怎样才能更改我的代码来做到这一点?

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;
        }
    }
}