30 October 2012

Count of Controls in Form using C#.Net

                Today , we will discuss about the Count of Controls in Form.The following are code for getting no of controls in Form.

Method for getting no of controls in Form:
  public IEnumerable<Control> GetAll(Control control, Type type)
            var controls = control.Controls.Cast<Control>();
            return controls.SelectMany(ctrl => GetAll(ctrl, type))
                                      .Where(c => c.GetType() == type);

 call Method in the Form Loading event(where ever you want)
var c = GetAll(this, typeof(Button));
MessageBox.Show("Total Controls: " + c.Count());

Total Controls: (no of Buttons in the form)

No comments: