Link to home
Start Free TrialLog in
Avatar of chaffinsjc
chaffinsjc

asked on

How to access programmatically created buttons

In a simple C# WinForm program, I can programmatically create five button controls with code such as:

...
InitializeComponent();
CreateRowOfButtons("r1");
//r1_Button2.BackColor = System.Drawing.Color.Red;  <===PROBLEM: this line does not compile
...

And then these two methods are added to Form1:

public void CreateRowOfButtons(string r)
{
    //Variables
    int X = 50; //initial location of button
    int Y = 50; //initial location of button

    for (int i = 1; i < 6; i++)
    {
        Button btn = new Button();
        btn.Name = r + "_Button" + i.ToString(); //r1_Button1, r1_Button2, r1_Button3...
        btn.Size = new System.Drawing.Size(30, 30); ;
        btn.Location = new System.Drawing.Point(X, Y);
        btn.Click += new System.EventHandler(AnyButtonClick);
        Controls.Add(btn);
        X += 40;
    }
}//end CreateRowOfButtons()

public void AnyButtonClick(Object sender, System.EventArgs e)
{
    Button myBtn = (Button)sender;
    myBtn.BackColor = Color.Red;
}//end AnyButtonClick()


PROBLEM: How do I access these buttons and get/set values after they are created but before user mouse events? Yes, I realize that during CreateRowOfButtons() I might set button r1_Button3 to "Red", but I wonder if there isn't some other way.
ASKER CERTIFIED SOLUTION
Avatar of graye
graye
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I don't thinks its that simple...i would debug and see if its getting to AnyButtonClick...because you code i correct...I'm sure intellisense pops up and shows you these options, yes?
SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
True, if you wanted to make changes to properties and execute methods that were specific to the Button class, you'd have to cast the this.Controls["r1_button2"] object back to a Button first.   But that wasn't part of the question.
Avatar of chaffinsjc
chaffinsjc

ASKER

I got both solutions to work. graye's answer was directly applicable to my problem (thank you so much). I also learned a lot and found the solution by Idle_Mind to be intriguing for possible future use. (thank you also).