How to access programmatically created buttons

Posted on 2009-12-29
Last Modified: 2012-05-08
In a simple C# WinForm program, I can programmatically create five button controls with code such as:

//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)
    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);
        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.
Question by:chaffinsjc
    LVL 41

    Accepted Solution

    The best way is to use the parent container's Controls collection.
    Since this is a WInForm app, it'd be as simple as:
                this.Controls["r1_Button2"].BackColor = Color.Red;
    LVL 21

    Expert Comment

    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?
    LVL 85

    Assisted Solution

    by:Mike Tomlinson
    I think graye's solution is applicable... make it work for any container on the form, though, use Controls.Find():

            Control[] matches = this.Controls.Find("r1_Button2", true);
            if (matches.Length > 0)
                Button btn  = (Button)matches[0];
                btn.BackColor = Color.Red;
    LVL 41

    Expert Comment

    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.

    Author Closing Comment

    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).

    Featured Post

    Find Ransomware Secrets With All-Source Analysis

    Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

    Join & Write a Comment

    Article by: Ivo
    C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
    This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    Sending a Secure fax is easy with eFax Corporate ( First, Just open a new email message.  In the To field, type your recipient's fax number You can even send a secure international fax — just include t…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    24 Experts available now in Live!

    Get 1:1 Help Now