检查ControlControl中的Control是否为Textbox

Fuz*_*ans 6 c# controls tabcontrol winforms

要清除我的文本框,我在表单中使用以下代码:

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

但现在我的文本框位于TabControl中.如何对文本框运行相同类型的检查,如果控件是文本框,则将值设置为"".我已经尝试过使用:

foreach(Control c in tabControl1.Controls)
Run Code Online (Sandbox Code Playgroud)

但这没效果.

Sam*_*ous 14

用这个

foreach (TabPage t in tabControl1.TabPages)
{
    foreach (Control c in t.Controls)
    { 
        if (c is TextBox || c is RichTextBox)
        {
            c.Text = "";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*ter 5

你也可以使用Enumerable.OfType.TextBox并且RichTextBox是唯一继承的控件TextBoxBase,这是您正在寻找的类型:

var allTextControls = tabControl1.TabPages.Cast<TabPage>() 
   .SelectMany(tp => tp.Controls.OfType<TextBoxBase>());
foreach (var c in allTextControls)
    c.Text = "";
Run Code Online (Sandbox Code Playgroud)