Without if/else
should not be possible, but you can you can use the operator &&
to do in a if
only:
private void maskedTextBoxEAN_Leave(object sender, CancelEventArgs e)
{
if (!string.IsNullOrWhiteSpace(maskedTextBoxEAN.Text) &&
!ValidaEAN13.CalculateChecksum(maskedTextBoxEAN.Text))
CaixaMensagemDeErro.Mensagem("O código EAN digitado não é valido.");
}
Depending on how the method CalculateChecksum
treats the argument, the IsNullOrWhiteSpace
may not be necessary.
As a suggestion, you can use the ErrorProvider
to inform the user of the error.
private void maskedTextBoxEAN_Leave(object sender, CancelEventArgs e)
{
if (!ValidaEAN13.CalculateChecksum(maskedTextBoxEAN.Text){
errorProvider1.SetError(maskedTextBoxEAN, "O código EAN digitado não é valido.");
//e.Cancel = true;
}
else
{
errorProvider1.SetError(maskedTextBoxEAN, String.Empty);
//e.Cancel = false;
}
}
You can also cancel user action by setting as true
to property Cancel
of control.
You can use the ternary operator
?
and:
but I don’t know if it’s a good option for nested ifs.– gato
This is not if/Else, it is only if nested. and for this there is the && or || operation to check more than one condition.
– Marco Souza