[英]Clear multiple text boxes with a button in C#
I use .NET framework 4. 我使用.NET framework 4。
In my form, I have 41 text boxes. 在我的表格中,我有41个文本框。
I have tried with this code: 我尝试过这段代码:
private void ClearTextBoxes()
{
Action<Control.ControlCollection> func = null;
func = (controls) =>
{
foreach (Control control in controls)
if (control is TextBox)
(control as TextBox).Clear();
else
func(control.Controls);
};
func(Controls);
}
And this code: 这段代码:
private void ClearTextBoxes(Control.ControlCollection cc)
{
foreach (Control ctrl in cc)
{
TextBox tb = ctrl as TextBox;
if (tb != null)
tb.Text = String.Empty;
else
ClearTextBoxes(ctrl.Controls);
}
}
This still does not work for me. 这仍然不适合我。
When I tried to clear with this code TextBoxName.Text = String.Empty;
当我试图用这个代码清除
TextBoxName.Text = String.Empty;
the textbox success cleared but one textbox, still had 40 textbox again. 文本框成功清除但是一个文本框,仍然有40个文本框。
How do I solve this? 我该如何解决这个问题?
EDIT 编辑
I put in this: 我投入了这个:
private void btnClear_Click(object sender, EventArgs e)
{
ClearAllText(this);
}
void ClearAllText(Control con)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
((TextBox)c).Clear();
else
ClearAllText(c);
}
}
but still not work. 但仍然不行。
Edit 编辑
I used panels and splitter. 我使用了面板和分离器。
void ClearAllText(Control con)
{
foreach (Control c in con.Controls)
{
if (c is TextBox)
((TextBox)c).Clear();
else
ClearAllText(c);
}
}
To use the above code, simply do this: 要使用上面的代码,只需执行以下操作:
ClearAllText(this);
Have you tried 你有没有尝试过
private void RecursiveClearTextBoxes(Control.ControlCollection cc)
{
foreach (Control ctrl in cc)
{
TextBox tb = ctrl as TextBox;
if (tb != null)
tb.Clear();
else
RecursiveClearTextBoxes(ctrl.Controls);
}
Step1: You need to go through all the Controls
in the Form
. 第1步:您需要浏览
Form
中的所有Controls
。
Step2: if a Control
is TextBox
then call Clear()
function. Step2:如果
Control
是TextBox
则调用Clear()
函数。
Try This: 尝试这个:
void clearText(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
((TextBox)c).Clear();
else
clearText(c);
}
}
public void ModifyControl<T>(Control root, Action<T> action) where T : Control
{
if (root is T)
action((T)root);
// Call ModifyControl on all child controls
foreach (Control control in root.Controls)
ModifyControl<T>(control, action);
}
private void button5_Click(object sender, System.EventArgs e)
{
clearText(this);
ModifyControl<TextBox>(splitContainer1, tb => tb.Text = "");
}
This works pretty well for myself. 这对我自己很有效。
void ClearTextBoxes(DependencyObject dObject)
{
TextBox tb = dObject as TextBox;
if (tb != null)
tb.Text = null;
foreach (DependencyObject obj in dObject.GetChildObjects())
ClearTextBoxes(obj);
}
And then simply call on it as you wish, for example, I am clearing all TextBoxes in a TabControl, which also includes the Tabs not on screen: 然后根据需要简单地调用它,例如,我正在清除TabControl中的所有TextBox,其中还包括不在屏幕上的选项卡:
ClearTextBoxes(CustomerTabControl);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.