C
C
Chvalov2014-10-09 23:59:24
Programming
Chvalov, 2014-10-09 23:59:24

C# WinForm how to clear all TextBoxes on a form?

Hello, tell me how to clear all TextBoxes on the form if some of them are on GroupBoxes
Tried this

foreach(Control c in Controls)
    if(c is TextBox)
        ((TextBox)c).Text = null;
And this
foreach (Control c in this.Controls)
            {
                if (c.GetType() == typeof(TextBox))
                    c.Text = string.Empty;
            }
But it only cleans those text fields that are just on the form, and not on GroupBoxes

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
StrangeAttractor, 2014-10-10
@Chvalov

You have to go inside. Here is the simplest way to modify your code:

foreach (Control c in Controls)
{
    if (c.GetType() == typeof (GroupBox))
        foreach (Control d in c.Controls)
            if (d.GetType() == typeof(TextBox))
                d.Text = string.Empty;

    if (c.GetType() == typeof(TextBox))
        c.Text = string.Empty;
}

And here is how (approximately, in fact, I would have made an extension method) I would have done:
private static void CleanAllTextBoxesIn(Control parent)
{
    foreach (Control c in parent.Controls)
    {
        if (c.GetType() == typeof(TextBox))
            c.Text = string.Empty;

        if (c.GetType() == typeof (GroupBox))
            CleanAllTextBoxesIn(c);
    }
}

private void CleanAllTextBoxesButton_Click(object sender, EventArgs e)
{
    CleanAllTextBoxesIn(this);
}

E
Espleth, 2014-10-10
@Espleth

Maybe I'm wrong, but Controls is the whole field, isn't it?
I didn’t use GroupBox, but I suspect that something like this is needed
, or maybe I’ll say garbage, but like this:
if (c is TextBox && c in groupBox)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question