2014-05-13 32 views
0

我在.NET 4上使用ASP.NET和C#開發一個簡單的應用程序。我有一個包含一些控件的項目模板的轉發器;其中之一是根據複雜的計算必須設置的標籤。我現在用的是OnItemDataBound事件來計算文本和在代碼中設置標籤的文本後面,像這樣:在Repeater中獲取子控件

protected void repRunResults_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 
    //capture current context. 
    Repeater repRunResults = (Repeater)sender; 
    Label laMessage = (Label)repRunResults.Controls[0].FindControl("laMessage"); 
    DSScatterData.RunResultsRow rRunResults = (DSScatterData.RunResultsRow)((DataRowView)(e.Item.DataItem)).Row; 

    //show message if needed. 
    int iTotal = this.GetTotal(m_eStatus, rRunResults.MaxIterations, rRunResults.TargetLimit); 
    if(iTotal == 100) 
    { 
     laMessage.Text = "The computed total is 100."; 
    } 
    else 
    { 
     laMessage.Text = "The computed total is NOT 100."; 
    } 
} 

我轉發的數據源中包含了幾行,所以我預料的每次曝光中繼器會調用事件處理程序並根據相關行中的數據顯示消息。但是,我只獲得一條消息,該消息出現在第一個轉發器展示中,但與數據源中最後一個行的數據匹配。

似乎每次觸發ItemDataBound事件時,我的代碼捕獲的控件都是相同的,因此我會在中繼器的每次展示中覆蓋消息。我已經完成了代碼,這就是它顯然正在發生的事情。

任何想法爲什麼?以及如何解決它?

注意。我的轉發器嵌套在另一個轉發器中。我不認爲這應該是相關的,但它可能是。

回答

2

你抓住第一個。您需要使用正在傳入的項目,例如:

protected void repRunResults_ItemDataBound(object sender, RepeaterItemEventArgs e) 
{ 
    //capture current context. 
    Repeater repRunResults = (Repeater)sender; 
    Label laMessage = e.Item.FindControl("laMessage"); //<-- Used e.Item here 
    DSScatterData.RunResultsRow rRunResults = (DSScatterData.RunResultsRow)((DataRowView)(e.Item.DataItem)).Row; 

    //show message if needed. 
    int iTotal = this.GetTotal(m_eStatus, rRunResults.MaxIterations, rRunResults.TargetLimit); 
    if(iTotal == 100) 
    { 
     laMessage.Text = "The computed total is 100."; 
    } 
    else 
    { 
     laMessage.Text = "The computed total is NOT 100."; 
    } 
} 
+0

+1謝謝。這正是問題所在! – CesarGon