Why would I get an "Invalid Cast" with this code?

240 Views Asked by At

I have a form which contains the following types of controls (only):

Button
ComboBox
Label
TextBox

I have a "Clear" button that calls this method:

private void ClearControls()
{
    foreach (TextBox txtbx in this.Controls)
    {
        if (txtbx != null)
        {
            txtbx.Text = string.Empty;
        }
    }
    foreach (ComboBox cmbx in this.Controls)
    {
        if (cmbx != null)
        {
            cmbx.SelectedIndex = -1;
        }
    }
}

...yet when I call it, the app hangs, and the log file says "Invalid cast" for that method. How could that be? It should deal with the TextBoxes and ComboBoxes, and disregard the rest - where could the invalid cast be?

3

There are 3 best solutions below

0
On BEST ANSWER

The foreach will try to cast the control to the specified type which will give that invalid cast exception, what you should do is:

foreach(Control ctrl in this.Controls)
{
    if(ctrl as TextBox != null)
    {
         //Textbox logic
    }
    if(ctrl as ComboBox!= null)
    {
         //ComboBox logic
    }
}
0
On

That's not what foreach does.

Specifying a type in a foreach loop does not skip items of other types; instead, it will cast every item to that type.

You can call .OfType<T>() to get the filtered list that you're looking for.

0
On

Based on Gunther's starting point, this works:

foreach (Control ctrl in this.Controls)
{
    if (ctrl as TextBox != null)
    {
        ctrl.Text = string.Empty;
    }
    if (ctrl as ComboBox != null)
    {
        ((ComboBox)ctrl).SelectedIndex = -1;
    }
}