【问题标题】:Finding Control return Null查找控件返回 Null
【发布时间】:2015-06-08 08:11:25
【问题描述】:

我有一个可以在 pnRoom(面板)中动态添加的控件

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

我在找到控件时收到 nullimgbtn

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

它总是返回null。我正在尝试,但没有运气。我需要你的帮助。谢谢!!!

对象引用未设置为对象的实例。

【问题讨论】:

    标签: c# asp.net controls imagebutton findcontrol


    【解决方案1】:
    • 您必须将FindControl 与您分配的Id 一起使用,因为您使用的是连续数字,所以您必须使用它而不是"imgbtn"
    • 您必须在您正在搜索的控件的NamingContainer 控件上使用FindControl。您在控件本身上使用了FindControl
    • 如果您在面板上使用循环,您将获得所有控件(非递归),因此您根本不需要使用FindControl。你想要所有ImageButton的,你可以使用Enumerable.OfType

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

    如果您不想使用所有ImageButton,或者您担心将来还有其他ImageButton 需要省略,更好的方法是给它们一个有意义的前缀和通过String.StartsWith过滤。

    假设你已经给了他们所有imgbtn_(并跟随一个数字):

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

    记得添加using System.Linq 如果还没有发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多