views:

149

answers:

6

How does one target a control by its Type?

I have a Control collection "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 each existing control (combobox,checkbox,etc.) by its specific Type with access to its specific properties. The way I'm doing it now only gives me access to generic control properties.

Can't I specify something like...

Combobox current = new ComboBox["Name"]; /// Referencing an Instance of ComboBox 'Name'

and then be given access to it's (already existing) properties for manipulation?

A: 

In order to access a control's specific properties, you have to cast it to its appropriate type. For example, if the item in your TargetControls collection was a textbox, you would have to say ((TextBox)TargetControls[0]).Text = 'blah';

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

David
+6  A: 

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

foreach (Control SubControl in page.Controls)
{
    if (SubControl is TextBox)
    {
        TextBox ctl = SubControl as TextBox;
    }
}
Am
+1 don't let anyone hit you with any nonsense about how you should use `as` instead of `is` and check for `null`.
MusiGenesis
i sure won't :)
Am
A: 

You'll need to cast the control to the right type of control before accessing any specific parameters.

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

Also you could add the controls to a generic dictionary<string, control> and use the control.name as the key there.

Ex.

Dictionary<string, Control> TargetControls  = new Dictionary<string, Control>();
chris.w.mclean
Thanks, that's exactly what I need. ComboBox c = ctrl as ComboBox;I now understand and have implemented casting. All the solutions seem cool but this is what harmonizes the best with my code.
zion
+1  A: 

Assuming you can use LINQ, and you're 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 items present.

Michael Petrotta
+1  A: 

What about the Find method?

Button btn = (Button)this.Controls.Find("button1", true)[0];
            btn.Text = "New Text";
Decker97
+2  A: 

You can use the OfType<T> extension method:

foreach (var textBox = page.Controls.OfType<TextBox>()) {
   // ...
}
Mehrdad Afshari