在WinForm里面有时候需要清空自己输入内容或是选择的选项,以便重新操作流程,那么一般你是怎么清空界面各个控件值的呢?如果窗体里面控件,尤其是TextBox控件比较多的时候,代码里面是不是要设置每个控件的Text属性值为空呢?下面我用这个例子,来探讨下清空界面控件值的小技巧。而且还能复用。不必每个窗体都做这些枯燥、无聊的工作。
一般的做法是在清除控件的事件里面添加下面这样的代码:
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
private void btnClear_Click(object sender, EventArgs e)
{
this.txbAccount.Text = "";
this.txbAddress.Text = "";
this.txbCmp.Text = "";
this.chkCash.Checked = false;
this.cmbDepart.Text = "";
//.............窗体里面各类要清空控件;
}
{
this.txbAccount.Text = "";
this.txbAddress.Text = "";
this.txbCmp.Text = "";
this.chkCash.Checked = false;
this.cmbDepart.Text = "";
//.............窗体里面各类要清空控件;
}
设想如果这样做,一个窗体我们清空界面需用10行代码,50个窗体那么就是500行代码,大量重复的劳动,如果我们用下面这种方法的话,那么项目里面代码量将大大减少,而且封装到类里面,可以重用。(当然这个函数还可以重载、扩展,以便适应不同的需求)
private void btnClear_Click(object sender, EventArgs e)
{
ClearCntrValue(this.pnlContent);
}
{
ClearCntrValue(this.pnlContent);
}
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
/// <summary>
/// 清除容器里面某些控件的值
/// </summary>
/// <param name="parContainer">容器类控件</param>
public void ClearCntrValue(Control parContainer)
{
for (int index = 0; index < parContainer.Controls.Count; index++)
{
// 如果是容器类控件,递归调用自己
if (parContainer.Controls[index].HasChildren)
{
ClearCntrValue(parContainer.Controls[index]);
}
else
{
switch(parContainer.Controls[index].GetType().Name)
{
case "TextBox":
parContainer.Controls[index].Text = "";
break;
case "RadioButton":
((RadioButton)(parContainer.Controls[index])).Checked = false;
break;
case "CheckBox":
((CheckBox)(parContainer.Controls[index])).Checked = false;
break;
case "ComboBox":
((ComboBox)(parContainer.Controls[index])).Text = "";
break;
}
}
}
}
/// 清除容器里面某些控件的值
/// </summary>
/// <param name="parContainer">容器类控件</param>
public void ClearCntrValue(Control parContainer)
{
for (int index = 0; index < parContainer.Controls.Count; index++)
{
// 如果是容器类控件,递归调用自己
if (parContainer.Controls[index].HasChildren)
{
ClearCntrValue(parContainer.Controls[index]);
}
else
{
switch(parContainer.Controls[index].GetType().Name)
{
case "TextBox":
parContainer.Controls[index].Text = "";
break;
case "RadioButton":
((RadioButton)(parContainer.Controls[index])).Checked = false;
break;
case "CheckBox":
((CheckBox)(parContainer.Controls[index])).Checked = false;
break;
case "ComboBox":
((ComboBox)(parContainer.Controls[index])).Text = "";
break;
}
}
}
}