Existing user validation in C#

Asked

Viewed 421 times

0

The function verificaLoginExistente warns that the login still exists, but still continues to the next line of code and registration. I want it to notify and return to register for a new name. My database has cod_user as a Primary key ,user (string) and password(varchar).

private bool VerificiarLoginExistente(string usuario)
    {
        bool resultado = false;
        string sql = "Select usuario From Usuario Where usuario = @usuario";
        Conexao cl = new Conexao();
        SqlConnection con = cl.conexao();
        SqlCommand cmdQry = con.CreateCommand(); 
        try
        {
            con.Open();

            using (SqlCommand command = new SqlCommand(sql))
            {
                command.Connection = con;
                command.Parameters.Add("@usuario", SqlDbType.VarChar).Value = tbUsuario;

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    resultado = reader.Read();
                    reader.Close();
                }
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Nome de usuário já existente");
        }

        finally
        {
            con.Close();
        }

        return resultado;
    }


    private void btnConfirmar_Click(object sender, EventArgs e)
    {
        Conexao cl = new Conexao();
        SqlConnection con = cl.conexao();
        SqlCommand cmdQry = con.CreateCommand();

            string usuario, senha, confirmasenha;

            usuario = tbUsuario.Text;
            senha = tbSenha.Text;
            confirmasenha = tbSenhaConfirm.Text;

            if ((usuario == "") || (senha == "") || (confirmasenha == ""))
            {
                {
                    MessageBox.Show("Campos obrigatórios");
                }
                return;
            }

            if((VerificiarLoginExistente(usuario))== true)
            {
                return;
            }

            if (senha == confirmasenha)
            {
                cmdQry.CommandText = "INSERT INTO Usuario (usuario, senha)" + "Values(@usuario,@senha)";

                cmdQry.Parameters.Add("@usuario", SqlDbType.VarChar, 50);
                cmdQry.Parameters.Add("@senha", SqlDbType.VarChar, 50);

                cmdQry.Parameters["@usuario"].Value = usuario;
                cmdQry.Parameters["@senha"].Value = senha;

                con.Open();
                cmdQry.ExecuteNonQuery();
                con.Close();

                MessageBox.Show("Cadastro efetuado com sucesso!");
                tbUsuario.Text = "";
                tbSenhaConfirm.Text = "";
                tbSenha.Text = "";
            }


            else
            {
                MessageBox.Show("Senhas não compatíveis !", "Aviso");
                tbSenhaConfirm.Text = "";
                tbSenha.Text = "";
                tbSenha.Focus();
            }



    }
  • which type of the user column? if varchar tries to add quotes like this ''@usuario''

1 answer

0


I think that’s not what you want, but if an Exception occurs means the user already exists, then you must change the code to return something in the block catch. No. NET, when an Exception occurs in a method with different return than void, the default value of the type defined in the return is returned, in your case when Exception occurs, the method returns false:

catch (Exception ex)
{
     MessageBox.Show("Nome de usuário já existente");
     return true; // < ---- ADICIONE ESTE RETORNO
}

If you say you see the message that the user already exists it means that an Exception has occurred in the method VerificiarLoginExistente.

I believe that there is something wrong with your code, because if the query and parameters are correct, no exception should be released. I believe the mistake is on the line:

 command.Parameters.Add("@usuario", SqlDbType.VarChar).Value = tbUsuario;

From your code, I understand that tbUsuario be a control TextBox. In this case, the correct one would be to pass the text value of the control and not the reference of the object:

 command.Parameters.Add("@usuario", SqlDbType.VarChar).Value = tbUsuario.Text;

Or better still, in order to use the method parameter being received without being used:

 command.Parameters.Add("@usuario", SqlDbType.VarChar).Value = usuario;

Finally, I suggest changing the Messagebox message displayed on catch, because if a query or connection to the bank, this does not mean that the user exists.

  • I made the changes, now it worked out, thanks, I was breaking my head here on time !

  • Good! If you helped and solved, please mark the answer as accepted so that other users can benefit too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.