user3415219
user3415219

Reputation: 1

Change properties of dynamically declared button

I have a dynamically created button in c#. The code is basically like this:

Button b = new Button();
b.Name = "dynabutt";
this.Controls.Add(b);

I want to have a non-dynamic button,button2, so that when I click button2, the color of the dynamic button changes. Is that possible? Thanks!

Upvotes: 0

Views: 161

Answers (2)

Elvedin Hamzagic
Elvedin Hamzagic

Reputation: 855

Of course, just declare variable b somewhere globally to be visible out of method (or assign to some other variable), for example:

public class Form1 : Form
{
    public Button button1 = null;
    public void SomeMethod()
    {
        Button b = new Button();
        b.Name = "dynabutt";
        this.Controls.Add(b);
        button1 = b;
        button1.BackColor = Color.Blue;
    }
    public void button2_Click(...)
    {
        if (button1 != null) button1.BackColor = Color.Red;
    }
}

Upvotes: 0

Selman Genç
Selman Genç

Reputation: 101681

You just need to attach an event handler to Click event of Button2.And if you know the name of dynamic button all you need to do is access it from your Controls collection and change it's color like this:

button2.Click += (s,e) => { this.Controls["dynabutt"].BackColor = Color.Blue; };

Upvotes: 1

Related Questions