Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access a Control in a collection by its Type?

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?

like image 870
zion Avatar asked Dec 22 '22 08:12

zion


2 Answers

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;
    }
}
like image 65
Amirshk Avatar answered Jan 10 '23 17:01

Amirshk


You can use the OfType<T> extension method:

foreach (var textBox = page.Controls.OfType<TextBox>()) {
   // ...
}
like image 20
mmx Avatar answered Jan 10 '23 16:01

mmx