Prevent user from saving information in the bank

Asked

Viewed 642 times

1

Hello I’m wearing Windows FORM C# Visual Studio, how do I prevent the user to save the information in the bank without filling in the required fields, that is to say (NOT NUL) from the bank all this via code C#. I tried with IF(){} as it is below, but it did not work.

    void IMPEDIRSALVAR()//Método impedi que o usuário salve as informações
    {
        if (txtNomeAluno.Text == "")
        {
            MessageBox.Show("Não é possivel criar um aluno sem o nome do aluno", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
            txtNomeAluno.Focus();
            if (mtbNascimentoAluno.Text == "")
            {
                MessageBox.Show("Não é possivel criar um aluno sem a Data de nascimento", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
                mtbNascimentoAluno.Focus();
            }

            if (mkb_Cpf.Text == "")
            {
                MessageBox.Show("Não é possivel criar um aluno sem O CPF do Responsável", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
                mkb_Cpf.Focus();
            }
            if (txtRG.Text == "")
            {
                MessageBox.Show("Não é possivel criar um aluno sem o RG do Responsável", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
                txtRG.Focus();
            }
            if (mkb_fone_contato.Text == "")
            {
                MessageBox.Show("Não é possivel criar um aluno sem o Fone de contato", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
                mkb_fone_contato.Focus();
            }
        }
        else
        {
            MessageBox.Show("Salvando");
        }

    }
  • All of your answers were unfortunately not valid. In the first txtbox (txtNomepupil) it works but if birth date and Cpf has Fazio it continues saving...

4 answers

3

The logic is wrong. Currently, to show "Saving", just fill in the student’s name - all other fields are optional.

if(nomeAluno  == ""){
    //...

    if(campo2  == "")
        //..
    if(campo3 == "")
        //...
}
else {
    //salvar
}

To make all fields mandatory, *if*s must be chained, instead of nested:

if(nomeAluno == "")
    //...
else if(campo2  == "")
    //..
else if(campo3 == "")
    //...
else {
    //salvar
}
  • I would recommend using string.Empty instead of using the "". Makes the purpose of comparison clearer.

3

What you can do to simplify validation is always use the return within each IF.

It is more or less what is suggested here: Replace Nested Conditional with Guard Clauses.

Of course this depends a lot also on your logic. Follow a code suggestion:

void IMPEDIRSALVAR()//Método impedi que o usuário salve as informações
{
    if (txtNomeAluno.Text.Equals(string.Empty))
    {
        MessageBox.Show("Não é possivel criar um aluno sem o nome do aluno", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
       txtNomeAluno.Focus();
       return;
    }
    if (mtbNascimentoAluno.Text.Equals(string.Empty))
    {
        MessageBox.Show("Não é possivel criar um aluno sem a Data de nascimento", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
        mtbNascimentoAluno.Focus();
        return;
    }

    // Nenhum erro...
    MessageBox.Show("Salvando");
}
  • It is an alternative to else if. In both cases he will only save if he did not enter any if. Goes from whoever wrote the code (preference for single point of Return)

2

Use the method IsNullOrEmpty (despite the check to null be irrelevant according to commenting of @star).

Additionally maintain a flat structure of ifs.If you will really validate everything by displaying MessageBox, else ifs prevent multiple errors from being displayed at once).

Finally, if you want to validate also if the text is not a blank string, take a look at the method IsNullOrWhiteSpace (or use txt.Text.All(char.IsWhiteSpace) if you don’t want to waste the check by null and void).

if (String.IsNullOrEmpty(txtNomeAluno.Text)) 
{
    MessageBox.Show("Não é possivel criar um aluno sem o nome do aluno", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
    txtNomeAluno.Focus();
}
else if (String.IsNullOrEmpty(mtbNascimentoAluno.Text))
{
    MessageBox.Show("Não é possivel criar um aluno sem a Data de nascimento", "Cadastrando Aluno", MessageBoxButtons.OK, MessageBoxIcon.Information);
    mtbNascimentoAluno.Focus();
}
// ....
else
{
    MessageBox.Show("Salvando");
}
  • 1

    Although it is good practice to use string.IsNullOrEmpty, in this particular case, it is irrelevant and does not solve the problem. TextBox.Text never and' null.

  • @dcastro, but the method also checks if it is empty, "orEmpty", so its validation is not wrong! And if you didn’t notice, he ends up doing the same thing as in his answer... ;D

  • @Brunocasali did not say the validation was wrong, said it was irrelevant. The answer "use the Isnullorempty method" is a wrong answer because it does not solve the OP problem.

  • @star, you’re right. I didn’t know it was impossible to assign null manually. Even so I keep my answer due to the structure, and additionally recommend the method Isnullorwhitespace for users of. NET 4 and higher.

1

Hello friends I managed to solve my problems with this method

public bool VerificarCamposEmBranco(Control ctrl)
{
    bool retorno = false;
    foreach (Control c in ctrl.Controls)
    {
        if (c is TextBox)
        {
            if (((TextBox)c).Text.Length <= 2)
            {
                //Campo ta em branco
                retorno = true;
                //((TextBox)c).BackColor = System.Drawing.Color.Red;
                MessageBox.Show("Preencha o campo" + c.Name);
            }
        }
    }

    return retorno;
}

Thank you so much for your help....

Browser other questions tagged

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