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.
Asked
Active
Viewed 2,747 times
4
-
Possible duplicate of http://stackoverflow.com/questions/1558127/how-can-i-get-all-controls-from-a-form-including-controls-in-any-container – Shamim Hafiz - MSFT Apr 26 '11 at 08:12
-
1Or http://stackoverflow.com/questions/949246/how-to-get-all-classes-within-namespace – František Žiačik Apr 26 '11 at 08:19
-
@Gunner, please read the question, he is talking about namespace not the form container in the link you specified. – Akash Kava Apr 26 '11 at 08:23
-
@Akash : please check the history - the title was changed from 'in a control' to 'in a namespace' it was quite an ambiguous question :) – Nick Apr 26 '11 at 08:56
3 Answers
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
-
-
"System.Window.Forms.TextBox" how can i create a textbox from this string value – deneme Apr 26 '11 at 08:44