有没有办法在文本框重命名为txtFName
,txtMName
等时立即清除它们......它们可能有各种以txt
开头的名称。这可能吗?像
private void btnReset_Click(object sender, EventArgs e)
{
txtFname.Clear();
txtLName.Clear();
txtUsername.Clear();
txtPasswrd.Clear();
/*So many textboxes to be cleared*/
}
替换为
private void ClearTextboxes(object obj)
{
/*codes to clear textboxes*/
}
然后我们可以在按钮点击事件中调用它
private void btnReset_Click(object sender, EventArgs e)
{
ClearTextboxes();
txtFname.Focus();
}
答案 0 :(得分:1)
此方法清除WinForm中的所有文本框
void ClearTextboxes(System.Windows.Forms.Control.ControlCollection ctrls)
{
foreach (Control ctrl in ctrls)
{
if (ctrl is TextBox)
((TextBox)ctrl).Text = string.Empty;
ClearTextboxes(ctrl.Controls);
}
}
你可以称之为
private void btnReset_Click(object sender, EventArgs e)
{
ClearTextboxes();
txtFname.Focus();
}
答案 1 :(得分:0)
您可以像这样遍历VisualTree中的所有文本框:
foreach (TextBox txtBx in FindVisualChildren<TextBox>(this))
{
txtBx.Clear();
}
FindVisualChildren:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
作为参数,您可以传递任何父级,它可以是StackPanel,或Grid或整个窗口。
答案 2 :(得分:0)
使用事件的一种方式是:
using System;
using System.Windows.Forms;
namespace textBoxs
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Subscribe();
}
private event Action ClearAll;
void Subscribe()
{
ClearAll += tbA.Clear;
ClearAll += tbB.Clear;
ClearAll += tbC.Clear;
}
private void button1_Click(object sender, EventArgs e)
{
ClearAll();
}
}
}