清除文本框和组合框c#
如果您正在使用的WinForms,你可以使用以下方法来清除所有想要的控制。
public void ClearTextBoxes(Control control)
{
foreach (Control c in control.Controls)
{
if (c is TextBox)
{
if (!(c.Parent is NumericUpDown))
{
((TextBox)c).Clear();
}
}
else if (c is NumericUpDown)
{
((NumericUpDown)c).Value = 0;
}
else if (c is ComboBox)
{
((ComboBox)c).SelectedIndex = 0;
}
if (c.HasChildren)
{
ClearTextBoxes(c);
}
}
}
然后激活它只需在表单中添加一个按钮,在后台代码如下。
private void button1_Click(object sender, EventArgs e)
{
ClearTextBoxes(this);
}
我可能是错的,但我不认为'HasChildren'的条件是必要的。 – AbZy 2013-02-14 17:20:29
它仍然没有工作,但与'if'声明只会经历的孩子,如果需要控制。 – eandersson 2013-02-14 17:31:06
感谢您的回答。它除了一件事情以外。 – user1903439 2013-02-14 17:35:29
如果是这样的WinForms通过所有的控制循环,然后重新设置
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = "";
}
else if (c is ComboBox)
{
((ComboBox)c).SelectedIndex = 0;
}
else if (c is NumericUpDown)
{
((NumericUpDown)c).Value= 0;
}
}
public void ClearTextBoxes(Control parent)
{
foreach(Control c in parent.Controls)
{
ClearTextBoxes(c);
if(c is TextBox) c.Text = string.Empty;
if(c is ComboBox) c.SelectedIndex = 0;
}
}
或
public void ClearTextBoxes(Control ctrl)
{
if (ctrl != null)
{
foreach (Control c in ctrl.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = string.empty;
}
if(c is ComboBox)
{
((ComboBox)c).SelectedIndex = 0;
}
ClearTextBoxes(c);
}
}
}
这是对的WinForms或WPF? – eandersson 2013-02-14 17:13:12
它是Windows窗体应用程序 – user1903439 2013-02-14 17:15:35