Link to home
Start Free TrialLog in
Avatar of Mike Eghtebas
Mike EghtebasFlag for United States of America

asked on

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

ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany 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
Avatar of Mike Eghtebas

ASKER

brb
SOLUTION
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
SOLUTION
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
SOLUTION
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