Looping through a datalist on another page

285 Views Asked by At

I have a datalist on an ascx page called shippingorders1 and I am trying to access the label called lblGiftCodeAmount. I am trying to loop through the datalist and retrieve the text of the label convert it to decimal and sum it. In a click event from my main page I have the following:

decimal addGiftCards = 0.0M;
foreach(DataListItem dli in (DataList)Page.FindControl("ShippingOrders1").FindControl("dlGiftCodeAmount").Items)
{
    addGiftCards += Convert.ToDecimal(((Label)dli.FindControl("lblGiftCodeAmount")).Text);
}

When this runs, I get a NullReferenceException on the line addGiftCards+= because of the label. In my Immediate window when I type in:

(DataList)Page.FindControl("ShippingOrders1").FindControl("dlGiftCodeAmount").Items

It shows me everything I expect to see, but when I type dli it returns the DataItem as null. I loop through this exact same datalist on another page, and it gives me no problems. So can anyone tell me what I am doing wrong and what I can do to get around this issue?

Any additional code need I will update the solution.

1

There are 1 best solutions below

0
On

DataItem is only available on initial page load; afterward, the data is kept through viewstate and DataItem is not available. It's only available again on rebind. Also, Items may also contain any header or footer you may have too, so FindControl wouldn't find a control in a different template.