How to prevent a command

Asked

Viewed 46 times

2

I would like to prevent my record from being saved if the radiobutton were not selected.

My code:

private void btnSalvar_Click(object sender, EventArgs e) {
    if ((rdbMasculino.Checked == false) && (rdbFeminino.Checked == false)) {
        MessageBox.Show("Preencha o Campo Sexo!");

        clnFuncionario Sexo = new clnFuncionario();

        Sexo.nome = txtNome.Text;
        if (rdbMasculino.Checked == true)
            Sexo.sexo = "Masculino";
        if (rdbFeminino.Checked == true)
            Sexo.sexo = "Feminino";

    } else {
        clnFuncionario Funcionario = new clnFuncionario();
        if (txtCodigo.Text != "") {
            Funcionario.cod_Funcionario = Convert.ToInt32(txtCodigo.Text);

        }

        Funcionario.sexo = rdbMasculino.Text;
        Funcionario.sexo = rdbFeminino.Text;

        if (ObjOperacao == clnFuncoesGerais.Operacao.Inclusao) {
            Funcionario.Gravar();

            MessageBox.Show("Dados Gravados com Sucesso! ", "Item novo " + txtNome.Text,
                MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}

If none of the radiobutton are marked, it shows the message, but after showing the message it saves the record anyway. I’d like the record to be saved only if one of the radiobutton are selected and would like to know if this code I made is good or can be improved.

2 answers

2

Simply exit the function after displaying the error message:

MessageBox.Show("Preencha o Campo Sexo!");
return; // sai da função

2


Maybe the lines below are not necessary because it is in the condition of both radiobutton are not marked.

clnFuncionario Sexo = new clnFuncionario();

Sexo.nome = txtNome.Text;
if (rdbMasculino.Checked == true)
    Sexo.sexo = "Masculino";
if (rdbFeminino.Checked == true)
    Sexo.sexo = "Feminino";

The code can go like this:

private void btnSalvar_Click(object sender, EventArgs e) {
    if ((rdbMasculino.Checked == false) && (rdbFeminino.Checked == false)) {
        MessageBox.Show("Preencha o Campo Sexo!");

    } else {
        clnFuncionario Funcionario = new clnFuncionario();

        Funcionario.nome = txtNome.Text;

        if (rdbMasculino.Checked == true)
            Funcionario.sexo = "Masculino";
        if (rdbFeminino.Checked == true)
            Funcionario.sexo = "Feminino";

        if (txtCodigo.Text != "") {
            Funcionario.cod_Funcionario = Convert.ToInt32(txtCodigo.Text);
        }

        if (ObjOperacao == clnFuncoesGerais.Operacao.Inclusao) {
            Funcionario.Gravar();

            MessageBox.Show("Dados Gravados com Sucesso! ", "Item novo " + txtNome.Text,
                            MessageBoxButtons.OK, 
                            MessageBoxIcon.Information);
        }
    }
}

Browser other questions tagged

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