0

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?

Renatas M.
  • 11,694
  • 1
  • 43
  • 62
Oshrib
  • 1,789
  • 12
  • 40
  • 67
  • 2
    My guess is that the ListView databinding hasn't actually happened when you call `checkTheImage()` (i.e. it's too early). You can quickly test this by using an event which happens later in the Page lifecycle, such as Page_PreRender. EDIT: On second thought, that might also be too early, rather try handle the ListView.Databound event, and try your code in there. – Daniel B Sep 08 '11 at 07:37
  • I agree with Daniel B. You should read [this](http://msdn.microsoft.com/en-us/library/ms178472.aspx#data_binding_events_for_databound_controls) – luviktor Sep 08 '11 at 07:49
  • The problem solved when i wrote the Page_PreRender. great ! thanks – Oshrib Sep 08 '11 at 08:14

1 Answers1

2

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)" ;
}
onof
  • 17,167
  • 7
  • 49
  • 85