[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 225
  • Last Modified:

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

0
Mike Eghtebas
Asked:
Mike Eghtebas
4 Solutions
 
ste5anSenior DeveloperCommented:
Cause there is no button (control) named medButton2 in this. Try this.myPanel2.FindControl().
0
 
Mike EghtebasDatabase and Application DeveloperAuthor Commented:
brb
0
 
Fernando SotoCommented:
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
 
AndyAinscowCommented:
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

Featured Post

Free recovery tool for Microsoft Active Directory

Veeam Explorer for Microsoft Active Directory provides fast and reliable object-level recovery for Active Directory from a single-pass, agentless backup or storage snapshot — without the need to restore an entire virtual machine or use third-party tools.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now