1

検索コントロール メソッドを使用して、デザイナーで画像を見つけて表示したいのですが、null が返され続けます。

これは私のコードです:

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

どんな助けでも大歓迎です、事前に感謝します

4

2 に答える 2

5

FindControl はコントロールの階層全体を検索しません。これは問題だと思います。

次の方法を試してください。

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;
}

使用法:

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

あなたの場合、親はこれです、例:

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

ID なしで使用でき、 T の最初のオカレンスが検索されます。

Image Showimage = FindControlRecursive<Image>(this, string.Empty);
于 2012-10-24T12:36:03.460 に答える
1
foreach (ImageShow image in imageList)
{
    Image showimage = FindControl(image.imageName) as Image;
    if(showimage != null)
    {
         showimage .Visible = true;
    }
}
于 2012-10-24T12:34:51.200 に答える