Resolved Color change issue in panels

miladel

Member
Joined
Aug 16, 2020
Messages
14
Programming Experience
Beginner
Dear all,
Some thing went wrong with my buttons backcolor when I want to change it with Click. with the code below every thing is fine, if i press the button1 it turn to green and butten2 turns to gray and vice versa. the problem is that when i put both of them in a panel, only the panels backcolor change and nothing else happens. could anyone please give me some solution about this?
thanks.

C#:
namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void changeBackColor(object sender, EventArgs e)
        {
            foreach (Control c in this.Controls)
            {
                if (c.Equals(sender))
                    c.BackColor = Color.LightGreen;
                else
                    c.BackColor = Color.LightGray;
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            changeBackColor(sender, null);
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            changeBackColor(sender, null);
        }
    }
}
Capture.JPG
 
Every control has a Controls property that is a collection of its child controls. If you move your Buttons from the form to a Panel then they are no longer in the form's Controls collection but the Controls collection of the Panel instead. I might rewrite that code recursively like this, which would handle any level of nesting:
C#:
private void Controls_Click(object sender, EventArgs e)
{
    ChangeBackColor((Control) sender, this);
}

private void ChangeBackColor(Control sender, Control container)
{
    foreach (Control child in container.Controls)
    {
        child.BackColor = child == sender
                              ? Color.LightGreen
                              : Color.LightGray;
        ChangeBackColor(sender, child);
    }
}
 
Every control has a Controls property that is a collection of its child controls. If you move your Buttons from the form to a Panel then they are no longer in the form's Controls collection but the Controls collection of the Panel instead. I might rewrite that code recursively like this, which would handle any level of nesting:
C#:
private void Controls_Click(object sender, EventArgs e)
{
    ChangeBackColor((Control) sender, this);
}

private void ChangeBackColor(Control sender, Control container)
{
    foreach (Control child in container.Controls)
    {
        child.BackColor = child == sender
                              ? Color.LightGreen
                              : Color.LightGray;
        ChangeBackColor(sender, child);
    }
}

work very well, thank you
 
Back
Top Bottom