How to validate Combobox?

Asked

Viewed 1,087 times

2

I have a Form registration in which you have some fields TextBox and ComboBox, I want my code to allow the user to register only when all fields are filled, but it is only validating TextBox, thus allowing the registration without selecting an option in the ComboBox. Follows the code:

   private void btnCadastrar_Click(object sender, EventArgs e)
        {
            if (txtSerie.Text == string.Empty) 
            {
                MessageBox.Show("Por favor, selecione uma série!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtSerie.BackColor = Color.Red;
            }

            else
            {
                MessageBox.Show("O CADASTRO FOI REALIZADO COM SUCESSO!", "Novo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                LimpaTela();
            }  
        }

1 answer

4


You can check the property .SelectedIndex of ComboBox. She returns a int representing the position(Index) of the item in ComboBox.

Add to that:

else if (suaComboBox.SelectedIndex.Equals(-1))
{
    //--> seu código para tratar           
}
  • Thank you very much, it worked! :)

Browser other questions tagged

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