Get c.SelectedItem in C # Controls

I am doing some validation functions for my project, but I'm stuck. I want to have one function to handle several different controls and errors.
Here is 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 call it this way:

private void txtNEAN_Validating(object sender, CancelEventArgs e)
{
    ValidateControls(txtNEAN);
}

This is great for text fields. But if I do this:

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 it normal to use? If not, what is the best alternative?
I would love to hear something!

+4
source share
3 answers

In this case, you should discard cinComboBox

else if (c is ComboBox)
     {
         if (((ComboBox)c).SelectedItem == null)
     }

, _Validating , . txtBox_Validating TextBoxes, comboBox_Validating comboboxes ..

+6

((ComboBox)c).SelectedItem

. , c ComboBox.

is as

// Converts c to a ComboBox. If c is not a ComboBox, assigns null to cmbControl

ComboBox cmbControl = c as ComboBox; 
if (cmbControl != null)
{
    if (cmbControl.SelectedItem != null)
    {
        // Do stuff here
    }
}
// Else it not a ComboBox
+2

, :

, . , . , InvalidCastException. # is as. , , . as , , . is . , , .


here

+1
source

Source: https://habr.com/ru/post/1655166/


All Articles