How do you access a control in a collection by type?

How to assign a control by its type?

I have a collection of Control "TargetControls"

List<Control> TargetControls = new List<Control>(); foreach (Control page in Tabs.TabPages) { foreach (Control SubControl in page.Controls) TargetControls.Add(SubControl); } foreach (Control ctrl in TargetControls)... 

I need to access every existing control (combobox, checkbox, etc.) by its specific type with access to its specific properties. The way I do it now gives me access to common management properties.

Could I indicate something like ...

Combobox current = new ComboBox ["Name"]; /// Link to the ComboBox instance 'Name'

and then access its (already existing) properties for manipulation?

+4
source share
6 answers

Before accessing any specific parameters, you will need to apply the control to the correct type of control.

 ComboBox c = ctrl as ComboBox; If (c != null) { //do some combo box specific stuff here } 

You can also add controls to the general dictionary<string, control> and use the name control.name as the key.

Ref.

 Dictionary<string, Control> TargetControls = new Dictionary<string, Control>(); 
+1
source

You can use the keyword to check for a specific type of control. If the control is of a specific type, execute the type.

 foreach (Control SubControl in page.Controls) { if (SubControl is TextBox) { TextBox ctl = SubControl as TextBox; } } 
+6
source

You can use the OfType<T> extension method:

 foreach (var textBox = page.Controls.OfType<TextBox>()) { // ... } 
+2
source

Assuming you can use LINQ and you are looking for (say) a Button control:

 var button = (from Control c in TargetControls where c.Name == "myName" && c is Button select c ).FirstOrDefault(); 

... which will give you the first Button control named "myName" in your collection or null if there are no such elements.

+1
source

What about the Find method?

 Button btn = (Button)this.Controls.Find("button1", true)[0]; btn.Text = "New Text"; 
+1
source

To access specific management properties, you must specify it in the appropriate type. For example, if the element in your TargetControls collection was a text field, you would say ((TextBox)TargetControls[0]).Text = 'blah';

If you don't know the types in advance, you can use reflection to access properties, but I need to have a better example of what you are trying to do first ...

0
source

All Articles