Question

I am using ASP.NET and C# on .NET 4 to develop a simple app. I have a repeater with an item template containing a few controls; one of them is a label that must be set depending on a complex calculation. I am using the OnItemDataBound event to compute the text and set the label's text in the code behind, like this:

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.";
    }
}

The data source for my repeater contains a few rows, so I would expect that each impression of the repeater would call the event handler and show the message according to the data in the associated row. However, I only get one message, which appears on the first repeater impression but matches the data for the last row in the data source.

It seems like every time the ItemDataBound event fires, the controls that my code captures are the same ones, so that I overwrite the message on every impression of the repeater. I have stepped through the code and this is what it is apparently happening.

Any idea why? And how to fix it?

Note. My repeater is nested inside another repeater. I don't think this should be relevant, but it might be.

Was it helpful?

Solution

You are grabbing the first one. You need to use the item that is being passed in like so:

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.";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top