1

I would like to use the find control method to find a image on the designer and make it visible, but i keep getting a null

This is my Code:

foreach (ImageShow image in imageList)
{
    Image Showimage = (Image)FindControl(image.imageName);
    Showimage.Visible = true;
}

Any help would be much appreciated, Thanks in advance

Alvin Wong
  • 12,210
  • 5
  • 51
  • 77
Jacob O'Brien
  • 713
  • 1
  • 8
  • 20

2 Answers2

5

FindControl does not search throughout a hierarchy of controls, I presume that this is a problem.

try using the following method :

public static T FindControlRecursive<T>(Control holder, string controlID) where T : Control
{
  Control foundControl = null;
  foreach (Control ctrl in holder.Controls)
  {
    if (ctrl.GetType().Equals(typeof(T)) &&
      (string.IsNullOrEmpty(controlID) || (!string.IsNullOrEmpty(controlID) && ctrl.ID.Equals(controlID))))
    {
      foundControl = ctrl;
    }
    else if (ctrl.Controls.Count > 0)
    {
      foundControl = FindControlRecursive<T>(ctrl, controlID);
    }
    if (foundControl != null)
      break;
  }
  return (T)foundControl;
}

Usage:

Image Showimage = FindControlRecursive<Image>(parent, image.imageName);

In your case parent is this, example :

Image Showimage = FindControlRecursive<Image>(this, image.imageName);

You can use it without ID, then will find first occurrence of T :

Image Showimage = FindControlRecursive<Image>(this, string.Empty);
Antonio Bakula
  • 20,445
  • 6
  • 75
  • 102
1
foreach (ImageShow image in imageList)
{
    Image showimage = FindControl(image.imageName) as Image;
    if(showimage != null)
    {
         showimage .Visible = true;
    }
}
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52