Click here to Skip to main content
15,892,737 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My app is crashing with "Invalid Cast Exception" on running the following code:

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


How could that be? Only TextBoxes are treated as TextBoxes, and only ComboBoxes are treated as ComboBoxes, so what's the problem?
Posted

foreach doesn't filter. And why iterate the collection twice?


C#
private void ClearControls()
{
    foreach ( Control c in this.Controls )
    {
        if ( c is ComboBox )
        {
            ((ComboBox) c).SelectedIndex = -1;
        }
        else if (c is TextBox )
        {
            ((TextBox) c).Text = string.Empty;
        }
    }
}
 
Share this answer
 
Comments
B. Clay Shannon 20-Nov-14 18:47pm    
Odd that "(TextBox)" is grayed out, as if it's redundant, but "(ComboBox)" is not.
BillWoodruff 21-Nov-14 13:01pm    
+5 This is a good answer, does not deserve a down-vote.
When your code iterates over the collection of Controls on the Form, the fact you specify a specific Control Type in your loops means that when the iterator comes to a Control of another Type you will get an "invalid cast" error.

Here's another, simpler way:
C#
foreach (TextBox tb in this.Controls.OfType<textbox>())
{
    tb.Text = string.Empty;
}

foreach (ComboBox cbx in this.Controls.OfType<combobox>())
{
    cbx.Text = string.Empty; // probably unnecessary
    cbx.SelectedIndex = -1;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900