<" /> <" /> <"/>

ASP.NET HiddenField value duplicated in Repeater after postback

1.3k views Asked by At

I have a Repeater and a Button control. Within the Repeater I have a HiddenField control:

<asp:Repeater runat="server" ID="rptItems">           
    <ItemTemplate>                          
        <asp:HiddenField runat="server" ID="hfReportId"></asp:HiddenField>
    </ItemTemplate>
</asp:Repeater>

<asp:Button runat="server" ID="btnSave" Text="Save" /> 

In the code behind, I am binding the ItemDataBound event handler to the Repeater in the Page_Load:

this.rptItems.ItemDataBound += new RepeaterItemEventHandler(rptItems_ItemDataBound);

In the event handler, I am setting the value of the HiddenField control programmatically:

protected void rptItems_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
    {
        var hfReportId = (HiddenField)e.Item.Controls[0].FindControl("hfReportId");
        hfReportId.Value = "TestValue";
    }    
}

So far, this works as expected and the value of the HiddenField is set to "TestValue".

The problem occurs on postback. If I click the Save button, the ItemDataBound event handler is fired again, and the value of the HiddenField is set once again, however the original value is maintained and I end up with a value of "TestValue,TestValue". I have swapped the HiddenField for a label control and this bahaviour does not happen.

I have stepped through the code, and when the ItemDataBound event handler fires on postback there is no value for the HiddenField.

Any help is appreciated.

2

There are 2 answers

0
Nikunj Soni On

You should have to bind event of item data bound in repeater in your aspx page like

OnItemDataBound="repeater_ItemDataBound"

use page load ispostback property while binding the repeater

if(!IsPostback)
{
   //Bind repeater
}

then in item data bound use

var hfReportId = (HiddenField)e.Item.FindControl("hfReportId");

instead of

var hfReportId = (HiddenField)e.Item.Controls[0].FindControl("hfReportId");

Happy Coding

0
Jipge On

I had the same problem with an asp:HiddenField inside a asp:Repeater. The issue was : On PostBack, the values inside my asp:Repeater where refreshed with DataBind() in the PageLoad() method instead of the ButtonSearch_click() event method. That's why I was still getting old values in asp:HiddenField of my asp:Repeater.