Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Losing value when clicking on button in ascx control that is rendered in asp:Repeater

I created a asp:Repeater that I fill with .ascx controls:

protected void Page_Load(object sender, EventArgs e)
{
    Repeater1.DataSource = listOfData;
    Repeater1.DataBind();            
}

On page I have:

<uc:Product runat="server"                                             
    ImportantData='<% #Eval("ImportantData") %>'                                               
    id="DetailPanel1" />

Inside Product.ascx.cs I have:

public int ImportantData{ get; set; }
protected void Page_Load(object sender, EventArgs e)
{

}

On Product.ascx I have:

<asp:ImageButton ID="btn_Ok" runat="server" 
     onclick="btn_Ok_Click"  
     ImageUrl="~/image.png" />

Problem is when I click on image button I get error:

A critical error has occurred. Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page...

I have tried to change first code to this:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Page.IsPostBack)
    {
        Repeater1.DataSource = listOfData;
        Repeater1.DataBind();            
    }
    // Repeater1.DataBind(); // and tried to put DataBind() here
}

But then when I click on image button ImportantData is empty.
What I did wrong here?

like image 920
1110 Avatar asked Mar 18 '14 11:03

1110


1 Answers

PageLoad is happening before your postback event, change your event to PreRender:

protected void Page_PreRender(object sender, EventArgs e)
{
    Repeater1.DataSource = listOfData;
    Repeater1.DataBind();            
}

This will bind your repeater after the postback and maintain your postback value.

Edit:

Here's a good picture showing the entire WebForms page lifecycle:

As you can see

ProcessPostData event is called AFTER Load event.

So you want to bind your Repeater after the PostData has been processed.

This can be done on PreRender

like image 80
Phill Avatar answered Sep 23 '22 08:09

Phill