Validating existing user in C #

0

The VerifyLoginExist function tells you that the login still exists, but still continues to the next line of code and signs in. I want her to call and return to register for a new name. My database has the cod_user as 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();
            }



    }
    
asked by anonymous 29.03.2016 / 21:34

1 answer

0

I think this is not what you want, but if an exception occurs the user already exists then you should change the code to return something in block catch . In .NET, when an exception occurs in a method with a return other than void , the default value of the type defined in the return is returned, in its case when the 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, an exception occurred in the VerificiarLoginExistente method.

I think there is something wrong with your code, because if the query and parameters are correct, no exception should be thrown. I think the error is on the line:

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

For your code, I understand that tbUsuario is a TextBox control. In this case, the correct 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 yet, in order to use the method parameter that is being received without being used:

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

Finally, I suggest changing the MessageBox message displayed in catch , because if a query error or connection to the database occurs, this does not mean that the user exists.

    
29.03.2016 / 21:52