I am making some validation functions for my project but I am stuck on something.
I want to have a single function to handle a couple of different controls and errors.
Here's my code:
private void ValidateControls(Control c)
{
if (c is TextBox)
{
if (c.Text == "")
{
epNew.SetError(c, "Something");
}
}
else if (c is ComboBox)
{
// What now?
// if (c.SelectedItem == null) does not work
}
}
And I am calling it like this:
private void txtNEAN_Validating(object sender, CancelEventArgs e)
{
ValidateControls(txtNEAN);
}
This works fine for textboxes. But if I do:
private void cbbEMerk_Validating(object sender, CancelEventArgs e)
{
ValidateControls(cbbEMerk);
}
if (c.SelectedItem == null)
for example does not work.
How can I achieve this? And is this okay to use? If not, what is a better alternative?
I'd love to hear anything!
You have to cast c
to a ComboBox
in this case
else if (c is ComboBox)
{
if (((ComboBox)c).SelectedItem == null)
}
By the way, don't create a _Validating
method for every control if they do the same thing. You can use a single one, or one txtBox_Validating
for TextBoxes, one comboBox_Validating
for comboboxes, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With