C# 检查控件是否为 TabControl 中的文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10728300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if Control is Textbox within TabControl
提问by Fuzz Evans
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:
但是现在我的文本框位于 TabControl 中。如何对文本框运行相同类型的检查,如果控件是文本框,请将值设置为“”。我已经尝试使用:
foreach(Control c in tabControl1.Controls)
But this did not work.
但这不起作用。
采纳答案by Samy Arous
use this
用这个
foreach (TabPage t in tabControl1.TabPages)
{
foreach (Control c in t.Controls)
{
if (c is TextBox || c is RichTextBox)
{
c.Text = "";
}
}
}
回答by Tergiver
tabControl1.Controls won't work because the tab control contains TabPages. You need to target the correct page.
tabControl1.Controls 将不起作用,因为选项卡控件包含TabPages。您需要定位正确的页面。
Alternately you can build a recursive method to do it:
或者,您可以构建一个递归方法来执行此操作:
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);
}
}
回答by Tim Schmelter
You can also use Enumerable.OfType. TextBoxand RichTextBoxare the only controls that inherit from TextBoxBase, this is the type you're looking for:
您也可以使用Enumerable.OfType. TextBox并且RichTextBox是唯一继承自 的控件TextBoxBase,这是您要查找的类型:
var allTextControls = tabControl1.TabPages.Cast<TabPage>()
.SelectMany(tp => tp.Controls.OfType<TextBoxBase>());
foreach (var c in allTextControls)
c.Text = "";
回答by jmic17986
Limpiar Controles
Limpiar 控件
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;
}
}

