Kate
Kate

Reputation: 945

How do I loop all buttons in my Form to change their text in C#

I am new to C# and I use windows forms. I have Form1 with 20 buttons on it (button1 to button20).

How can I loop all those 20 buttons and change their text to for example "Hello" text?

Anyone knows how to achieve this? Thank you

Upvotes: 0

Views: 285

Answers (2)

Craig W.
Craig W.

Reputation: 18155

A simple loop will work find until you introduce containers into the page (groupboxes, tabs, etc). At that point you need a recursive function.

private void ChangeButtons(Control.ControlCollection controls)
{
    for (int i = 0; i < controls.Count; i++)
    {
        // The control is a container so we need to look at this control's
        // children to see if there are any buttons inside of it.
        if (controls[i].HasChildren)
        {
            ChangeButtons(controls[i].Controls);
        }

        // Make sure the control is a button and if so disable it.
        if (controls[i] is Button)
        {
            ((Button)controls[i]).Text = "Hello";
        }
    }
}

You then call this function passing in the Form's control collection.

ChangeButtons(this.Controls);

Upvotes: 1

Arian Motamedi
Arian Motamedi

Reputation: 7413

Somewhere in your form's code behind:

foreach(var btnControl in this.Controls.OfType<Button>())
{
    btnControl.Text = "Hello";
}

Upvotes: 4

Related Questions