Remember IsPostBack check with databound controls to avoid "Invalid postback or callback argument" error

Ref: http://aspadvice.com/blogs/joteke/archive/2006/08/27/Remember-IsPostBack-check-with-databound-controls-to-avoid-_2200_Invalid-postback-or-callback-argument_2200_-error.aspx

Ref: http://www.telerik.com/community/forums/thread/b311D-bcbdet.aspx

If you face this error: Invalid postback or callback argument error too often when working with databound controls. For example scenario like this

<asp:Repeater ID="Repeater1" runat="server"  >
        <ItemTemplate>
            <table>
                <tr>
                    <td><asp:ImageButton ID="ImageButton1" ImageUrl="~/AspInsider.gif" runat="server" OnClick="ImageButton_Click"  /></td>
                    <td><asp:ImageButton ID="ImageButton2" ImageUrl="~/AspInsider.gif" runat="server" OnClick="ImageButton_Click" /></td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:Repeater> 

protected void Page_Load(object sender, EventArgs e)
    {
        //Forgetting IsPostBack check is one possible source of problems
        if (!Page.IsPostBack)
        {
            List<int> ints = new List<int>();
            ints.Add(1);
            ints.Add(2);
            ints.Add(3);

            Repeater1.DataSource = ints;
            Repeater1.DataBind();
        }
      
    }

    protected void ImageButton_Click(object sender, EventArgs e)
    {
       
        ImageButton imgBtn = (ImageButton)sender;

        //Locating the row the ImageButton is on
        RepeaterItem ritem = (RepeaterItem)imgBtn.NamingContainer;

        Response.Write("Row index of the RepeaterItem containing ImageButton you clicked is:" + ritem.ItemIndex);
 
    }

 

If you omit the Page.IsPostBack check, you note that page starts to throw exceptions about "Invalid postback or callback argument".

If you use datasource controls, issue is most likely that you call DataBind() either for Page or your control, in Page_Load manually without IsPostBack check. Putting the call inside if(!Page.IsPostBack){...} should solve the problem. Also note that data bound controls with datasource source controls are able to do databinding automatically, and with correct timing so that you wouldn't get errors.

posted @ 2008-06-30 13:22  Vincent Yang  阅读(450)  评论(0编辑  收藏  举报