简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM