C# 从多个控件获取值的通用方法
我有一个C# 从多个控件获取值的通用方法,c#,winforms,controls,C#,Winforms,Controls,我有一个表单,有多个不同的控件,如组合框、文本框和复选框。我正在寻找一种通用的方法,在循环这些控件时从这些控件获取值 例如,类似这样的内容: foreach(Control control in controls) { values.Add(control.Value); } public delegate object GetControlValue(Control aCtrl); private static Dictionary<Type, GetCont
表单
,有多个不同的控件,如组合框
、文本框
和复选框
。我正在寻找一种通用的方法,在循环这些控件时从这些控件获取值
例如,类似这样的内容:
foreach(Control control in controls)
{
values.Add(control.Value);
}
public delegate object GetControlValue(Control aCtrl);
private static Dictionary<Type, GetControlValue> _valDelegates;
public static Dictionary<Type, GetControlValue> ValDelegates
{
get
{
if (_valDelegates == null)
InitializeValDelegates();
return _valDelegates;
}
}
private static void InitializeValDelegates()
{
_valDelegates = new Dictionary<Type, GetControlValue>();
_valDelegates[typeof(TextBox)] = new GetControlValue(delegate(Control aCtrl)
{
return ((TextBox)aCtrl).Text;
});
_valDelegates[typeof(CheckBox)] = new GetControlValue(delegate(Control aCtrl)
{
return ((CheckBox)aCtrl).Checked;
});
// ... other controls
}
public static object GetValue(Control aCtrl)
{
GetControlValue aDel;
if (ValDelegates.TryGetValue(aCtrl.GetType(), out aDel))
return aDel(aCtrl);
else
return null;
}
是否可能或是否需要分别处理每个控件?尝试以下方法:
Panel myPanel = this.Panel1;
List<string> values = new List<string>();
foreach (Control control in myPanel.Controls)
{
values.Add(control.Text);
}
如果每个控件都是文本框,那么文本解决方案是可以的,但是如果您有一些标签,那么您将在值中以标签文本结束,除非您用if填充代码。更好的解决方案可能是定义一组委托,对于每种控件,这些委托返回被认为是值的内容(例如,文本框的文本和复选框的复选框),将它们放入字典中,并使用它们获取每个控件的值。代码可以是这样的:
foreach(Control control in controls)
{
values.Add(control.Value);
}
public delegate object GetControlValue(Control aCtrl);
private static Dictionary<Type, GetControlValue> _valDelegates;
public static Dictionary<Type, GetControlValue> ValDelegates
{
get
{
if (_valDelegates == null)
InitializeValDelegates();
return _valDelegates;
}
}
private static void InitializeValDelegates()
{
_valDelegates = new Dictionary<Type, GetControlValue>();
_valDelegates[typeof(TextBox)] = new GetControlValue(delegate(Control aCtrl)
{
return ((TextBox)aCtrl).Text;
});
_valDelegates[typeof(CheckBox)] = new GetControlValue(delegate(Control aCtrl)
{
return ((CheckBox)aCtrl).Checked;
});
// ... other controls
}
public static object GetValue(Control aCtrl)
{
GetControlValue aDel;
if (ValDelegates.TryGetValue(aCtrl.GetType(), out aDel))
return aDel(aCtrl);
else
return null;
}
您是否获得了一个公共属性,例如Text
?您可以使用.Text
属性-哦,是的,由于某种原因,在MSDN上没有找到它。谢谢。