我记得有人一段时间之前问过类似的问题,但是我做了搜索却没有找到任何内容。
我正在尝试想出将表单上的所有控件清除回到它们的默认值的最简洁方法(例如,清除文本框,取消复选框勾选)。
您会如何处理这个问题?
public static class extenstions
{
private static Dictionary<Type, Action<Control>> controldefaults = new Dictionary<Type, Action<Control>>() {
{typeof(TextBox), c => ((TextBox)c).Clear()},
{typeof(CheckBox), c => ((CheckBox)c).Checked = false},
{typeof(ListBox), c => ((ListBox)c).Items.Clear()},
{typeof(RadioButton), c => ((RadioButton)c).Checked = false},
{typeof(GroupBox), c => ((GroupBox)c).Controls.ClearControls()},
{typeof(Panel), c => ((Panel)c).Controls.ClearControls()}
};
private static void FindAndInvoke(Type type, Control control)
{
if (controldefaults.ContainsKey(type)) {
controldefaults[type].Invoke(control);
}
}
public static void ClearControls(this Control.ControlCollection controls)
{
foreach (Control control in controls)
{
FindAndInvoke(control.GetType(), control);
}
}
public static void ClearControls<T>(this Control.ControlCollection controls) where T : class
{
if (!controldefaults.ContainsKey(typeof(T))) return;
foreach (Control control in controls)
{
if (control.GetType().Equals(typeof(T)))
{
FindAndInvoke(typeof(T), control);
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Controls.ClearControls();
}
编辑:我刚刚添加了一个通用的ClearControls方法,它可以清除该类型的所有控件,可以像这样调用:
this.Controls.ClearControls<TextBox>();
目前它只能处理顶级控件,而不能深入到分组框和面板中。
我知道这是一个老问题,但是我想发表一下我的看法。这是我用于表单清除的辅助类。
using System;
using System.Windows.Forms;
namespace FormClearing
{
class Helper
{
public static void ClearFormControls(Form form)
{
foreach (Control control in form.Controls)
{
if (control is TextBox)
{
TextBox txtbox = (TextBox)control;
txtbox.Text = string.Empty;
}
else if(control is CheckBox)
{
CheckBox chkbox = (CheckBox)control;
chkbox.Checked = false;
}
else if (control is RadioButton)
{
RadioButton rdbtn = (RadioButton)control;
rdbtn.Checked = false;
}
else if (control is DateTimePicker)
{
DateTimePicker dtp = (DateTimePicker)control;
dtp.Value = DateTime.Now;
}
}
}
}
}
我可以从任何表单中通过传递表单对象作为参数来调用该方法。
Helper.ClearFormControls(this);
这里是我在第一个回答中提出的相同解决方案,但使用VB语言。由于VB不支持lambdas中的无返回函数,在VB10发布前,这是我们能做到的最好的方法:
VB解决方案:
Public Module Extension
Private Sub ClearTextBox(ByVal T As TextBox)
T.Clear()
End Sub
Private Sub ClearCheckBox(ByVal T As CheckBox)
T.Checked = False
End Sub
Private Sub ClearListBox(ByVal T As ListBox)
T.Items.Clear()
End Sub
Private Sub ClearGroupbox(ByVal T As GroupBox)
T.Controls.ClearControls()
End Sub
<Runtime.CompilerServices.Extension()> _
Public Sub ClearControls(ByVal Controls As ControlCollection)
For Each Control In Controls
If ControlDefaults.ContainsKey(Control.GetType()) Then
ControlDefaults(Control.GetType()).Invoke(Control)
End If
Next
End Sub
Private _ControlDefaults As Dictionary(Of Type, Action(Of Control))
Private ReadOnly Property ControlDefaults() As Dictionary(Of Type, Action(Of Control))
Get
If (_ControlDefaults Is Nothing) Then
_ControlDefaults = New Dictionary(Of Type, Action(Of Control))
_ControlDefaults.Add(GetType(TextBox), AddressOf ClearTextBox)
_ControlDefaults.Add(GetType(CheckBox), AddressOf ClearCheckBox)
_ControlDefaults.Add(GetType(ListBox), AddressOf ClearListBox)
_ControlDefaults.Add(GetType(GroupBox), AddressOf ClearGroupbox)
End If
Return _ControlDefaults
End Get
End Property
End Module
调用:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Controls.ClearControls()
End Sub
您可以使用循环控制
foreach (Control ctrl in this)
{
if(ctrl is TextBox)
(ctrl as TextBox).Clear();
}
public void ClearControl(Control control)
{
TextBox tb = control as TextBox;
if (tb != null)
{
tb.Text = String.Empty;
}
// repeat for combobox, listbox, checkbox and any other controls you want to clear
if (control.HasChildren)
{
foreach(Control child in control.Controls)
{
ClearControl(child)
}
}
}
在清除文本属性之前,您不希望仅仅检查控件类型。
实现一个接口,比如IClearable(像Bill K建议的那样)在一组派生控件上会减少此函数的长度,但需要在每个控件上进行更多的工作。
私有的无返回值函数 FormReset() { ViewState.Clear(); Response.Redirect(Request.Url.AbsoluteUri.ToString()); }
我正在使用这种方法来清除Windows表单上的控件。这是文本框、数字增减器和日期选择器的示例。
public void Clear()
{
foreach (var item in this.Controls)
{
if (item is TextBox)
{
TextBox text = (TextBox)item;
text.Clear();
//text.Text = "";
//text.Text=String.Empty;
//text.Text = null;
}
else if (item is NumericUpDown)
{
NumericUpDown numeric = (NumericUpDown)item;
numeric.Value = 0;
}
else if (item is DateTimePicker)
{
DateTimePicker dateTimePicker = (DateTimePicker)item;
dateTimePicker.Value = DateTime.Now;
}
}
//Focus the cursor where you want to
txtBookName.Focus();
}
//Clears the textboxes
WebControlUtilities.ClearControls<TextBox>(myPanel.Controls);
Clear方法适用于页面或母版页。控件集合类型可能会有所不同,例如Form、ContentPlaceHolder等。
/// <summary>
/// Clears Text from Controls...ie TextBox, Label, anything that implements ITextBox
/// </summary>
/// <typeparam name="T">Collection Type, ie. ContentPlaceHolder..</typeparam>
/// <typeparam name="C">ie TextBox, Label, anything that implements ITextBox</typeparam>
/// <param name="controls"></param>
public static void Clear<T, C>(ControlCollection controls)
where C : ITextControl
where T : Control
{
IEnumerable<T> placeHolders = controls.OfType<T>();
List<T> holders = placeHolders.ToList();
foreach (T holder in holders)
{
IEnumerable<C> enumBoxes = holder.Controls.OfType<C>();
List<C> boxes = enumBoxes.ToList();
foreach (C box in boxes)
{
box.Text = string.Empty;
}
}
}
/// <summary>
/// Clears the text from control.
/// </summary>
/// <typeparam name="C"></typeparam>
/// <param name="controls">The controls.</param>
public static void ClearControls<C>(ControlCollection controls) where C : ITextControl
{
IEnumerable<C> enumBoxes = controls.OfType<C>();
List<C> boxes = enumBoxes.ToList();
foreach (C box in boxes)
{
box.Text = string.Empty;
}
}