0

I have a control that add dynamically in pnRoom (panel)

 ImageButton imgbtn = new ImageButton();
 imgbtn = new ImageButton();
 imgbtn.Height = 25;
 imgbtn.CssClass = "bulb";
 imgbtn.ID = i++;
 pnRoom.Controls.Add(imgbtn);

And i'm received null value when finding control imgbtn

 protected void LoadBulb()
    {           
            foreach (Control c in pnRoom.Controls)
            {
                ImageButton img = (ImageButton)c.FindControl("imgbtn");
                img.ImageUrl = "~/path/images/bulb_yellow_32x32.png";
            }
    }

It's allways return null. I'm try but no luck. i need your help. Thanks !!!

Object reference not set to an instance of an object.

TaW
  • 53,122
  • 8
  • 69
  • 111
huy cao
  • 28
  • 8

1 Answers1

2
  • You have to use FindControl with the Idyou have assigned, since you use a consecutive number you have to use that instead of "imgbtn".
  • You have to use FindControl on the NamingContainer-control of that which you are searching. You are using FindControl on the control itself.
  • If you use a loop on the panel you get all controls inside(non-recursive), so you don't need to use FindControl at all. You want all ImageButton's, you can use Enumerable.OfType:

    foreach(var img in  pnRoom.Controls.OfType<ImageButton>())
    {
         img.ImageUrl = "~/path/images/bulb_yellow_32x32.png";
    }
    

if you don't want to take all ImageButton's or you're afraid that in future there are other ImageButton's that you want to omit, a better approach is to give them a meaningful prefix and filter via String.StartsWith.

Presuming that you have given them all imgbtn_ (and following a number):

var imgBtns = pnRoom.Controls.OfType<ImageButton>().Where(i => i.ID.StartsWith("imgbtn_"));
foreach(var img in  imgBtns)
{
    // ...
}

Remember to add using System.Linq if not already happened.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939