Search code examples
c#comboboxcastingtextboxruntime-type

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


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?


Solution

  • 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
        }
    }