views:

578

answers:

1

I have a usercontrol that provides voting buttons (for a SO type voting model) - it contains a private int member that retains the id of the record. Outside a repeater, it functions just fine - postbacks work, and the correct id is retained in the user control.

Inside the repeater, an itemdatabound event handler associates the correct ID with the usercontrol and it works correctly - displays the correct vote count from the database. When one of the voting buttons is pressed, though, it fires a postback to the usercontrol and the control has lost the contents of its private int member so it no longer functions.

I've tried both re-databinding the usercontrol on postback, and binding it only on the initial load - the problem is the same both ways.

How do I get the usercontrol to retain the value of that int across postbacks?

+4  A: 

Have you tried putting the value in viewstate ?

public string Id{
    get
    {
        return this.ViewState["Value"] == null ?
            0 :
            (int)this.ViewState["Value"];
    }
    set { this.ViewState["Value"] = value; }
}
mathieu
Yes, I would think you've correctly identified the cause and the solution.
Cerebrus
Thanks! That did the trick. Any insight as to why I need to do that for the control in the repeater, but the same control works properly outside of it?
azollman
Private member variables in controls aren't serialized as part of the viewstate and thus aren't restored on postback. The above solution is correct if you want to retain a private var in the viewstate. Another option would be to use a hidden text box and then it would get automatically restored.
DancesWithBamboo