2011-09-08 72 views
0

我有一個錯誤:ListView控件的FindControl錯誤

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

爲了下一個代碼:

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

代碼 - 背後:

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

,並在Page_Load中的代碼:

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

爲什麼我得到錯誤?我的代碼有什麼問題?

+2

我的猜測是,當您調用checkTheImage()時(即太早),ListView數據綁定實際上並未發生。您可以通過使用稍後在Page生命週期中發生的事件(如Page_PreRender)來快速測試此事件。編輯:第二個想法,這可能還爲時過早,而是嘗試處理ListView.Databound事件,並嘗試在那裏你的代碼。 –

+0

我同意丹尼爾B.你應該閱讀[this](http://msdn.microsoft.com/en-us/library/ms178472.aspx#data_binding_events_for_databound_controls) – luviktor

+0

當我寫Page_PreRender時,問題解決了。太好了!謝謝 – Oshrib

回答

2

您必須指定項目:

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

因爲ListView控件呈現給每個孩子項目image1的控制。要更改所有圖像:

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

謝謝。現在我沒有得到錯誤...但它不顯示noImage.jpg ...爲什麼? – Oshrib

+0

當我編寫Page_PreRender時,問題就解決了。太好了!謝謝 – Oshrib