从多个控件获取值的通用方法

时间:2012-06-14 12:57:33

标签: c# winforms controls

我的Form有多个不同的控件,例如ComboBoxTextBoxCheckBox。我正在寻找一种通用的方法来获取这些控件的值,同时循环它们。

例如,像这样:

foreach(Control control in controls)
{
    values.Add(control.Value);
}

是否可以或我是否需要单独处理每个control

2 个答案:

答案 0 :(得分:2)

试试这个:

Panel myPanel = this.Panel1;

List<string> values = new List<string>();

foreach (Control control in myPanel.Controls)
{
    values.Add(control.Text);
}

但请确保您只获得所需的控件。您可以像

一样检查类型
if(control is ComboBox)
{
    // Do something
}

答案 1 :(得分:2)

如果每个Control都是TextBox,Text解决方案就可以了,但如果你有一些Label,你最终会得到值中标签的文本,除非你用if填充你的代码。一个更好的解决方案可能是定义一组委托,为每种Control返回被认为是值的值(例如TextBox的文本和CheckBox的Checked),将它们放在字典中,并使用它们来获取值每个控制。代码可能是这样的:

    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;
    }

然后你可以写:

        foreach (Control aCtrl in Controls)
        {
            object aVal = GetValue(aCtrl);
            if (aVal != null)
                values.Add(aVal);
        }
相关问题