Kieran Benton
Kieran Benton

Reputation: 8900

Retrieve DataItem from RepeaterItem after databinding (during an event handler)

I'm trying to find a way to to do something that I think must be possible but I'm just missing the point on - so hopefully someone can give me a bit of a nudge :)

I'm utilising databinding in ASP.NET (viewstate turned off - so using controlstate for a few things here and there) to render a repeater (repeaterPriceClasses) that has a repeater within each itemtemplate (repeaterPriceBands). Basically this renders a table out of some text and a dropdownlist in each cell.

I'm trying to find a way to enumerate the repeaterOuter inside the event handler of a button to give me a list of all of the originally bound elements that have now got a dropdownlist with a value of >0, along with what that value is.

public Dictionary<Price, int> SelectedPrices
{
    get
    {
        var sel = new Dictionary<Price, int>();
        foreach(RepeaterItem itemClass in repeaterPriceClasses.Items)
        {
            var repeaterPriceBands = itemClass.FindControl("repeaterPriceBands") as Repeater;

            foreach(RepeaterItem itemBand in repeaterPriceBands.Items)
            {
                var context = (Price)itemBand.DataItem;
                var listQty = itemBand.FindControl("listQty") as DropDownList;

                if(listQty.SelectedValue.ToInt32() > 0)
                {
                    sel.Add(context, listQty.SelectedValue.ToInt32());
                }
            }
        }
        return sel;
    }
}

Now this fails because the itemBand.DataItem is always null after databinding has finished.

What technique should I use to get around this?

  1. Hidden field with primary keys in it (not ideal as can be abused and adds weight to the page)

  2. Lookup from original cached data based on indexes (just seems wrong)

  3. or something else/better...?

EDIT: Is there any more information that I could provide to help this get answered?

Upvotes: 4

Views: 7282

Answers (1)

Kirtan
Kirtan

Reputation: 21685

You can try adding extra attributes to your HTML elements in the ItemDataBound event when DataItem is available.

ddlSomething.Attributes["Attribute1"] = dataItemObject.PropertyName;

[Edit] Apart from using attributes, you can render some array containing JSON objects like this, for each row.

var repeaterItemAttributes = [ { Prop1: val1, Prop2: val2, ... }, { ... }, ... ]

So, by using this, you won't have to render the attributes, and your code will be XHTML compliant too (tho its not required). You can then loop through the object array and read any property you like. You can also apply the light encryption you were talking about to the property values. [/Edit]

Upvotes: 1

Related Questions