Check if the control is a text field in TabControl

To clear the text fields, I used the following code in the form:

foreach (Control c in this.Controls)
{
    if (c is TextBox || c is RichTextBox)
    {
        c.Text = "";
    }
}

But now my text fields are inside TabControl. How can I run the same type of validation for text fields, and if the control is a text field, set the value to "". I have already tried using:

foreach(Control c in tabControl1.Controls)

But that did not work.

+5
source share
4 answers

use this

foreach (TabPage t in tabControl1.TabPages)
{
    foreach (Control c in t.Controls)
    { 
        if (c is TextBox || c is RichTextBox)
        {
            c.Text = "";
        }
    }
}
+11
source

You can also use Enumerable.OfType. TextBoxand RichTextBoxare the only controls that inherit from TextBoxBase, this is the type you are looking for:

var allTextControls = tabControl1.TabPages.Cast<TabPage>() 
   .SelectMany(tp => tp.Controls.OfType<TextBoxBase>());
foreach (var c in allTextControls)
    c.Text = "";
+5
source

tabControl1.Controls , TabPage s. .

Alternatively, you can create a recursive method for this:

static void RecurseClearAllTextBoxes(Control parent)
{
    foreach (Control control in parent.Controls)
    {
        if (control is TextBox || control is RichTextBox)
            control.Text = String.Empty;
        else
            RecurseClearAllTextBoxes(control);
    }

    if (parent is TabControl)
    {
        foreach (TabPage tabPage in ((TabControl)parent).TabPages)
            RecurseClearAllTextBoxes(tabPage);
    }
}
+1
source

Limpiar controles

        foreach (Control C in GB.Controls)
        { 
            if(C is TextBox)
            {
                (C as TextBox).Clear();
            }
            if(C is DateTimePicker)
            {
                (C as DateTimePicker).Value = DateTime.Now;
            }
            if (C is ComboBox)
            {
                (C as ComboBox).SelectedIndex = 0;
            }
        }
+1
source

All Articles