deneme
deneme

Reputation: 77

How can I get all the controls in a namespace?

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.

Upvotes: 4

Views: 2862

Answers (3)

jonsca
jonsca

Reputation: 10381

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

Upvotes: 0

Farzin Zaker
Farzin Zaker

Reputation: 3606

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

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

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

Upvotes: 6

Related Questions