How to prevent a command

2

I would like to prevent my record from being saved if 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 is checked, it shows the message, however, after showing the message it saves the record anyway. I would like the registry to only be saved if one of the radiobutton is selected and I would like to know if this code I made is good or better.

    
asked by anonymous 08.10.2016 / 22:12

2 answers

2

Maybe the lines below are not necessary because it goes into the condition that 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 looks 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);
        }
    }
}
    
09.10.2016 / 00:11
2

Simply exit the function after displaying the error message:

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