0

When using a foreach loop to change controls' attributes I often find that certain attributes are missing.

If I say btnMyButton. I can then select ".SelectedForeColor" from intellisense.

However, if I say foreach(Control x in this.Controls) or, foreach(Button x in this.Controls), the attribute ".SelectedForeColor" is missing from intellisense.

//This Works

        btnMyButton.SelectedForeColor = Color.Blue;

This Does Not Work. The attribute is not available

        foreach (Control x in this.Controls)
        {                
            if (x is Button)
            {
                ((Button)x).SelectedForeColor = Color.Blue;                    
            }
        }

Any thoughts on how to set Control.SelectedForeColor via a foreach loop would be appreciated.

2 Answers 2

1

You can change your for loop to this:

foreach (Buttonx in this.Controls.OfType<Button>())

Then, you'll have the correct type and your properties are available.

Sign up to request clarification or add additional context in comments.

Comments

0

In the first example you are directly using the variable the Button was assigned to, which is of type Button.

In the foreach you are iterating over a collection of Controls. While the Buttons can "fit" into the control type, you only got access to Control properties and functions. This is just 101 of class behavior, section Polymorphy.

So these two examples are not even remotely similar scenarios. You either need to only retrieve buttons to iterate over (which should get you a collection of button instances), or continue to do the check+cast you are already doing.

A third option is to create your own collection of buttons to iterate over, using the names you already got something like:

Button[] ArrayOfButtons = { btnMyButton, btnCancel, btnOK, btnAccept };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.