ListView FindControl error

拜拜、爱过 提交于 2020-02-07 07:25:47

问题


I have the next error:

System.NullReferenceException – Object reference not set to an instance of an object.

To the next code:

<asp:ListView ID="LV1"  runat="server" DataSourceID="LinqDataSource">
  <ItemTemplate>
     <asp:Image ID="Image1" Width="100px" Height="100px" runat="server" ImageUrl='<%# Eval("ImageUrl") %>' />
     //....and so on till the 
</asp:ListView>

The code - behind:

protected void checkTheImage()
{
    ((Image)LV1.FindControl("Image1")).ImageUrl = "(noImage.jpg)" ;
}

and the code on page_load:

protected void Page_Load(object sender, EventArgs e)
{
    checkTheImage();
}

Why i got the error? what is wrong in my code?


回答1:


You have to specify the item:

protected void checkTheImage()
{
    ((Image)LV1.Items[0].FindControl("Image1")).ImageUrl = "(noImage.jpg)" ;
}

because the ListView render an Image1 control for each child item. To change all images:

protected void checkTheImage()
{
   foreach(ListViewItem item in LV1.Items)
      ((Image)item.FindControl("Image1")).ImageUrl = "(noImage.jpg)" ;
}


来源:https://stackoverflow.com/questions/7344593/listview-findcontrol-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!