Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Control is Textbox within TabControl

To clear my text boxes I was using the following code in a form:

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

But now my text boxes reside within a TabControl. How can I run this same type of check for text boxes, and if the control is a textbox, set the value to "". I have already tried using:

foreach(Control c in tabControl1.Controls)

But this did not work.

like image 855
Fuzz Evans Avatar asked May 23 '12 21:05

Fuzz Evans


2 Answers

use this

foreach (TabPage t in tabControl1.TabPages)
{
    foreach (Control c in t.Controls)
    { 
        if (c is TextBox || c is RichTextBox)
        {
            c.Text = "";
        }
    }
}
like image 143
Samy Arous Avatar answered Sep 24 '22 07:09

Samy Arous


You can also use Enumerable.OfType. TextBox and RichTextBox are the only controls that inherit from TextBoxBase, this is the type you're looking for:

var allTextControls = tabControl1.TabPages.Cast<TabPage>() 
   .SelectMany(tp => tp.Controls.OfType<TextBoxBase>());
foreach (var c in allTextControls)
    c.Text = "";
like image 28
Tim Schmelter Avatar answered Sep 24 '22 07:09

Tim Schmelter