Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get c.SelectedItem in Controls C#

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!

like image 955
Sj03rs Avatar asked Jan 06 '23 08:01

Sj03rs


1 Answers

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.

like image 102
Raphaël Althaus Avatar answered Jan 13 '23 12:01

Raphaël Althaus