Reputation: 10247
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?
Upvotes: 0
Views: 229
Reputation: 10247
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;
}
}
Upvotes: -2
Reputation: 918
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
}
}
Upvotes: 5
Reputation: 887433
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.
Upvotes: 6