多控件获取值的通用方法

3

我有一个包含多个不同控件的表单,如ComboBoxTextBoxCheckBox。我正在寻找一种通用的方法,在循环遍历这些控件时获取它们的值。

例如,像这样:

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

这是否可能,还是我需要分别处理每个控件


1
你是否正在获取一个常见的属性,例如 Text - Joel Etherton
1
你可以使用.Text属性 - http://msdn.microsoft.com/fr-fr/library/system.windows.forms.control.text - Arnaud F.
哦,对了,之前在MSDN上不知道为什么找不到。非常感谢。 - mooper
2个回答

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
}

2

如果每个控件都是文本框,那么文本解决方案是可以的,但是如果你有一些标签,你最终会在值中得到标签的文本,除非你用if语句填充你的代码。更好的解决方案可能是定义一组委托,针对每种控件返回被认为是值的内容(例如,文本框的文本和复选框的选中状态),将它们放入字典中,并使用它们来获取每个控件的值。代码可能类似于以下内容:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接