VoVb
VoVb

Reputation: 89

C# Global Component Code

i'm new to C# i've been messing around to discover this language so far i've wrote many programs in my quest but now i'm stuck with one thing, i can't explain by words but codes can say what i want so here we go i know it's silly program but it's for education purpose only :D

Private void change()
        {
anycontrol.BackColor = Color.Gold; // when this function called the control's BackColor will Change to gold
        }
// example
private void TextBox1_Focused(object sender, EventArgs e)
{
Change(); // this suppose to change the color of the controls which is now textbox1 i want it to work on other controls such as buttons progressbars etc
}

now after i explained my problem i may ask you if you can to help it will be appreciated.

Upvotes: 0

Views: 216

Answers (1)

Sean Airey
Sean Airey

Reputation: 6372

You can create a method that takes a Control and a Color as a parameter, and anything that inherits from Control (i.e. TextBox, DropDownList, Label etc.) will work with this:

void SetControlBackgroundColour(Control control, Color colour)
{
    if (control != null)
    {
        control.BackColor = colour;
    }
}

In your example, you could use it like this:

private void TextBox1_Focused(object sender, EventArgs e)
{
    SetControlBackgroundColour(sender as Control, Color.Gold);
}

In response to the comments, you could then use this method in a recursive method that will set the background colour for each control on the form:

void SetControlBackgroundColourRecursive(Control parentControl, Color colour)
{
    if (parentControl != null)
    {
        foreach (Control childControl in parentControl.Controls)
        {
            SetControlBackgroundColour(childControl, colour);

            SetControlBackgroundColourRecursive(childControl);
        }
    }
}

And then call this function on your Form object (this) in your Form1_Load method (assuming the form is called Form1):

protected void Form1_Load(object sender, EventArgs e)
{
    SetControlBackgroundColourRecursive(this, Color.Gold);
}

Upvotes: 3

Related Questions