Click here to Skip to main content
15,946,525 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have 3 Windows forms let Suppose
Form1
Form2
Form3

Form1 has 3 textBox Control
Form2 has 6 textBox Control
Form3 has 14 textBox Control

I want a Function that Accepts form object and clear all textboxes in that form.
I use this code but its not working (No Error, Just No Output).

C#
public void ClearTextBoxes(Form form)
{
     foreach (Control control in form.Controls)
     {

           if (control.GetType() == typeof(TextBox))
           {

                control.Text = "";

           }

     }
}

//Calling this Function
var fm1 = new Form1();
ClearTextBoxes(fm1);

//Smilarly From Form2 and So on
var fm2 = new Form2();
ClearTextBoxes(fm2);


Please Help me so i can acomplish this task..
Posted
Comments
Thomas Daniels 30-Aug-14 13:47pm    
Do you have any nested TextBoxes (TextBoxes in other controls such as a Panel)?
Ghalib Mirza 30-Aug-14 14:04pm    
Yes I have Group Box as Parent of textboxes..

In your comment, you said:
Quote:
Yes I have Group Box as Parent of textboxes..

Your method does not look at nested controls (controls inside controls). Try a recursive solution:
C#
public void ClearTextBoxes(Control.ControlCollection ctrlCollection)
{
    foreach (Control ctrl in ctrlCollection)
    {
        if (ctrl is TextBoxBase)
        {
            ctrl.Text = String.Empty;
        }
        else
        {
            ClearTextBoxes(ctrl.Controls);
        }
    }
}

To use the method on your form, use this code:
C#
ClearTextBoxes(this.Controls);
 
Share this answer
 
v4
Comments
Ghalib Mirza 30-Aug-14 14:31pm    
Thankyou Sir "@ProgramFOX",
Your example is working absolutely fine for me..
This encourages me and enhance my knowledge. Thnx again..
Ghalib Mirza 30-Aug-14 14:48pm    
Sorry to disturb you sir ..
i wanna ask you one more thing if there is a ComboBox insted of a TextBox and what if i want all combo boxes set to Zero Index...?
Sergey Alexandrovich Kryukov 31-Aug-14 1:58am    
How about doing a bit by yourself using the idea. Do you know how many classes in .NET FCL? Are you going to ask the same question on different classes?
And better use Solution 2, it is more correct, especially if you take into account my comments.
—SA
Thomas Daniels 31-Aug-14 5:13am    
You can actually do almost the same; just replace TextBoxBase with ComboBox and inside the if statement, set the index to zero. Note that you need to cast the Control to a ComboBox before you can do that.
Sergey Alexandrovich Kryukov 31-Aug-14 1:54am    
Voted 4. It's not good to compare by System.Type, because it would filter out objects of the classes derived from TextBoxBase.
Solution 2 is better (is of "is" also, use of string.Empty,), but still there is one problem.
—SA
If you have nested controls you have to make it recursive try following function.
C#
public void EmptyFormControls(Control control)
{
    if (control is TextBox)
    {
        ((TextBox)control).Text = string.Empty;
    }

    for (int i = 0; i < control.Controls.Count; i++)
    {
       EmptyFormControls(control.Controls[i]);
    }
}

You can call it as follows.
C#
Form1 obj = new Form1();
EmptyFormControls(obj);
 
Share this answer
 
Comments
Ghalib Mirza 30-Aug-14 14:35pm    
Sir @DineshMaind Sorry to say you, there is a logical problem in your code your code is not working for me. Hence i would analyse your code and make it correct thnx for your kind response...
Sergey Alexandrovich Kryukov 31-Aug-14 2:00am    
Where do you see a problem?
—SA
Sergey Alexandrovich Kryukov 31-Aug-14 1:57am    
This solution is much better than Solution 1, but I voted 4, too: you should have used the class System.Windows.Forms.TextBoxBase, not System.Windows.Forms.TextBox, because the classes which could be considered text box classes are derived from TextBoxBase, moreover, it is recommended to use TextBoxBase as an immediate base class (which is designed to be used that way), not TextBox.

Besides, the loop will be simpler if you change it to foreach.

—SA
Ghalib Mirza 31-Aug-14 2:43am    
@Sergey Alexandrovich This code is not working for me even i ammend this code as:

public void EmptyFormControls(Control control)
{
if (control is TextBoxBase)
{
((TextBoxBase)control).Text = string.Empty;
}

for (int i = 0; i < control.Controls.Count; i++)
{
EmptyFormControls(control.Controls[i]);
}
}

///Calling this function
var obj = new Form1();
EmptyFormControls(obj);

Still its not working..

Have a better solution Kindly provide me with code examples.. Thnx
DineshMaind 31-Aug-14 3:09am    
If you want to use it for your current form just call EmptyFormControls(this); it will work definitely. As I am using it in my live projects...
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:
C#
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);
    } //loop
} //ClearControls

Usage:
C#
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;
    }));
} //test


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
 
Share this answer
 
v3
Comments
Thomas Daniels 31-Aug-14 13:44pm    
+5, good answer!
Sergey Alexandrovich Kryukov 31-Aug-14 14:52pm    
Thank you very much.
—SA
DineshMaind 31-Aug-14 13:53pm    
my +5, very nice and generalized solution. Highly useful for me.
Sergey Alexandrovich Kryukov 31-Aug-14 14:52pm    
Thank you very much.
—SA
Ghalib Mirza 1-Sep-14 6:47am    
I m speechless for your Solution .. amazing solution.. but unfortunately i know nothing about Generic Class (Sad but true). The word Generic is new for me, now i add it to "Have to Learn" Sticky note..
Thanx for the solution.
To make it really generic to use, I would create a Dictionary to set the clear method for each type, and then have a non-generic method that can clear an entire control hierarchy by using the actions defined in the dictionary. This also gives a clear separation of defining actions and running them.

C#
//...

private Dictionary<Type, Action<object>> actions = new Dictionary<Type, Action<object>>
        {
            { typeof(TextBox), ctrl => ((TextBox)ctrl).Text = string.Empty },
            { typeof(ComboBox), ctrl => ((ComboBox)ctrl).SelectedIndex = -1 },
        };

//...

private void ClearChildControls(Control parent)
{
    foreach (Control child in parent.Controls)
    {
        var controlType = child.GetType();

        if (actions.ContainsKey(controlType))
        {
            actions[controlType](child);
        }

        ClearChildControls(child);
    }
}

//...
 
Share this answer
 

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