Ghalib Mirza wrote:
Yes now its works fine for both textboxes and Comboboxes Thanx Sir @Dinesh and Sir @Sergey Alexandrovich thnx for making me correct…
Well, no, then the answers published so far are not universal enough. If you really need some action for those two or more different types, you rather need one common generic method. I wrote it for you:
using System;
using System.Windows.Forms;
static void ClearControls<CTRL>(Control parent, Action<CTRL> clearMethod) where CTRL: Control {
foreach (Control child in parent.Controls) {
CTRL targetChild = child as CTRL;
if (targetChild != null)
clearMethod(targetChild);
ClearControls(child, clearMethod);
}
}
Usage:
static void Test(Control parent) {
ClearControls<TextBox>(parent, new Action<TextBox>((child) => {
child.Text = string.Empty;
}));
ClearControls<ComboBox>(parent, new Action<ComboBox>((child) => {
if (child.Items.Count > 0)
child.SelectedIndex = 0;
}));
}
Note the use of the operator
as
, instead of
is
. If is good when you need both type check and type cast: the type check actually is the comparison of the type cast result with null.
Of course, the action can be anything of this profile, not only "clear". You can also add parameters, for something else.
—SA