NullReferenceException error, c#

This code generates a few buttons dynamically:
private void makeButtonFor(int id, string caption)
    {
        Button b = new Button();
        {
            var temp = "medButton" + id.ToString();
            b.ID = temp; 
            b.Text = caption;
            var captionButton = (caption.Substring(0, 6) == "Region") ? "RegionButton" : "medCtrButtonStyle";
            b.ControlStyle.CssClass =captionButton;
            myPanel2.Controls.Add(b);
            b.Click += new System.EventHandler(medCtrSubmit_click);

        };
    }

Open in new window

The values in temp are like "medButton1",  "medButton2", etc.

Question: Why btn is null at line 5 in the code below?
            
if (IsPostBack)
            {
               Button btn = (Button)this.FindControl("medButton2");
               btn.BackColor = System.Drawing.Color.FromArgb(0, 138, 105, 212);
               System.Drawing.Color.FromArgb(16, btn2.BackColor);
            }

Open in new window

LVL 34
Mike EghtebasDatabase and Application DeveloperAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
Cause there is no button (control) named medButton2 in this. Try this.myPanel2.FindControl().
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
brb
0
Fernando SotoRetiredCommented:
Hi eghtebas;

I think what @steSan was trying to say is that it should be this.

Button btn = (Button)myPanel2.FindControl("medButton2");

Because of the following reason, from Microsoft documentation Control.FindControl Method (String):

This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls.
0
james2432Commented:
n general, dynamically added controls will need to be re-added on each server round trip. The exception are control content of controls that maintain ViewState. Insure that your controls are added during PageInit which occurs before ViewState is loaded.

Then you can simply reference your controls to acquire their contents, values, selected indexes etc.
0
AndyAinscowFreelance programmer / ConsultantCommented:
Also check you do actually call the makeButtonFor function for the medButton2, your question implies the code does work for medButtton1 (which does reside on the sub panel)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.