开发者

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"

    开发者_Python百科    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?


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


You can use the OfType<T> extension method:

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


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


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.


What about the Find method?

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


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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜