Как я могу получить все элементы управления из формы, включая элементы управления в любом контейнере?

Мне нужен, например, способ отключить все кнопки в форме или проверить данные всех текстовых полей. Любые идеи? Заранее спасибо!


person Luiscencio    schedule 13.10.2009    source источник


Ответы (4)


Самым простым вариантом может быть каскадирование:

public static void SetEnabled(Control control, bool enabled) {
    control.Enabled = enabled;
    foreach(Control child in control.Controls) {
        SetEnabled(child, enabled);
    }
}

или похожие; вы, конечно, можете передать делегата, чтобы сделать его довольно общим:

public static void ApplyAll(Control control, Action<Control> action) {
    action(control);
    foreach(Control child in control.Controls) {
        ApplyAll(child, action);
    }
}

тогда такие вещи, как:

ApplyAll(this, c => c.Validate());

ApplyAll(this, c => {c.Enabled = false; });
person Marc Gravell    schedule 13.10.2009
comment
На самом деле не отвечает на вопрос заголовка - как получить все элементы управления, а не редактировать их свойства. - person n00dles; 10.07.2017
comment
@ n00dles, чтобы процитировать вопрос: мне нужно, например, отключить все кнопки в форме - person Marc Gravell; 10.07.2017
comment
После того, как я написал комментарий, я подумал ... может быть, это заголовок, который нужно отредактировать. Я был немного раздражен, потому что искал ответ на заглавный вопрос. Сделал это сейчас. (От одного Марка к другому!) - person n00dles; 11.07.2017

Я предпочитаю ленивый (итераторный) подход к проблеме, поэтому вот что я использую:

/// <summary> Return all of the children in the hierarchy of the control. </summary>
/// <exception cref="ArgumentNullException"> Thrown when one or more required arguments are null. </exception>
/// <param name="control"> The control that serves as the root of the hierarchy. </param>
/// <param name="maxDepth"> (optional) The maximum number of levels to iterate.  Zero would be no
///  controls, 1 would be just the children of the control, 2 would include the children of the
///  children. </param>
/// <returns>
///  An enumerator that allows foreach to be used to process iterate all children in this
///  hierarchy.
/// </returns>
public static IEnumerable<Control> IterateAllChildren(this Control control,
                                                      int maxDepth = int.MaxValue)
{
  if (control == null)
    throw new ArgumentNullException("control");

  if (maxDepth == 0)
    return new Control[0];

  return IterateAllChildrenSafe(control, 1, maxDepth);
}


private static IEnumerable<Control> IterateAllChildrenSafe(Control rootControl,
                                                           int depth,
                                                           int maxDepth)
{
  foreach (Control control in rootControl.Controls)
  {
    yield return control;

    // only iterate children if we're not too far deep and if we 
    // actually have children
    if (depth >= maxDepth || control.Controls.Count == 0)
      continue;

    var children = IterateAllChildrenSafe(control, depth + 1, maxDepth);
    foreach (Control subChildControl in children)
    {
      yield return subChildControl;
    }
  }
}
person zastrowm    schedule 23.05.2013

Также попробуйте:

public List<Control> getControls(string what, Control where)
    {
        List<Control> controles = new List<Control>();
        foreach (Control c in where.Controls)
        {
            if (c.GetType().Name == what)
            {
                controles.Add(c);
            }
            else if (c.Controls.Count > 0)
            {
                controles.AddRange(getControls(what, c));
            }
        }
        return controles;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var c = getControls("Button", this);

    }
person Luiscencio    schedule 13.10.2009

Я искал решение для того же, чтобы включать / отключать элементы управления в зависимости от типа, поэтому я придумал этот подход, аналогичный подходу Luiscencio (вы также можете изменить его, чтобы получить все элементы управления или изменить другие свойства).

public static void setEnabled (ControlCollection cntrList ,bool enabled,List<Type> typeList = null)
{
    foreach (Control cntr in cntrList)
    {
        if (cntr.Controls.Count == 0)
            if (typeList != null)
            {
                if (typeList.Contains(cntr.GetType()))
                    cntr.Enabled = enabled;
            }
             else
                cntr.Enabled = enabled;
        else
                setEnabled(cntr.Controls, enabled, typeList);
    }
}

public void loadFormEvents()
{
    List<Type> list = new List<Type> ();
    list.Add(typeof(TextBox));
    setEnabled(frm.Controls ,false,list);
}
person MoeCaruso    schedule 21.02.2018