4

How can I get all the controls in a namespace? For example, I want to get the controls in System.Windows.Forms: TextBox, ComboBox etc.

alex
  • 3,710
  • 32
  • 44
deneme
  • 77
  • 2
  • 6

3 Answers3

6

The notion of a control in a namespace is a bit unclear. You could use reflection to get classes in an assembly in a given namespace which derive from a particular base type. For example:

class Program
{
    static void Main()
    {
        var controlType = typeof(Control);
        var controls = controlType
            .Assembly
            .GetTypes()
            .Where(t => controlType.IsAssignableFrom(t) && 
                        t.Namespace == "System.Windows.Forms"
            );
        foreach (var control in controls)
        {
            Console.WriteLine(control);
        }
    }
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • I wonder whether you need to do a 'startswith' rather than equality in the namespace comparison so that controls in child namespaces are included. – Nick Apr 26 '11 at 08:18
  • @Nick, yes this is a possibility and it will depend on the specific requirements. – Darin Dimitrov Apr 26 '11 at 08:19
  • Genius. With this I can even get all controls from a custom namespace from my app. Just what I've searched for. Thanks! – C4d Jun 07 '16 at 11:50
5

this will return all classes in a specified namespace :

string @namespace = "System.Windows.Forms";

var items = (from t in Assembly.Load("System.Windows.Forms").GetTypes()
        where t.IsClass && t.Namespace == @namespace
        && t.IsAssignableFrom(typeof(Control))
        select t).ToList();
Farzin Zaker
  • 3,578
  • 3
  • 25
  • 35
0

Your form object has a Controls member, which is of type ControlCollection. It is essentially a list (with some other interfaces under the hood) of all of the controls.

EDIT: As per your comment, you need to cast the control back into a textbox. First you must identify it as a control.

foreach (var control in controls)
{
    if(control is TextBox)
    {
        (control as TextBox).Text = "Or whatever you need to do";
    }
}
jonsca
  • 10,218
  • 26
  • 54
  • 62