This is a migrated thread and some comments may be shown as answers.

[Solved] ASP.NET throws StackOverflowException because RadGrid raises PageSizeChanged event after "DataBind" method

1 Answer 176 Views
Grid
This is a migrated thread and some comments may be shown as answers.
massimo mannoni
Top achievements
Rank 1
massimo mannoni asked on 05 Apr 2013, 02:50 PM
Hi
I have a RadGrid which uses custom data binding (and of course custom paging and sorting). here is the markup:

<telerik:RadGrid runat="server" ID="grdArticoliCommentabili"
        AutoGenerateColumns="false" AllowPaging="true"
        OnItemCommand="grdArticoliCommentabili_ItemCommand"
        OnDetailTableDataBind="grdArticoliCommentabili_DetailTableDataBind"
        OnItemDataBound="grdArticoliCommentabili_ItemDataBound"
        AllowFilteringByColumn="true"
        OnPageIndexChanged="grdArticoliCommentabili_PageIndexChanged"
        OnPageSizeChanged="grdArticoliCommentabili_PageSizeChanged">
        <GroupingSettings CaseSensitive="false" />
        <MasterTableView DataKeyNames="id_articolo" CommandItemDisplay="Top" NoMasterRecordsText="<%$ Resources:Labels,NessunDato %>"
            NoDetailRecordsText="<%$ Resources:Labels,NessunDato %>">
            <CommandItemTemplate>
                <table cellpadding="4" cellspacing="0" width="100%">
                    <tr>
                        <td style="text-align: right; vertical-align: bottom;">
                            <asp:LinkButton ID="btnAggiorna" runat="server" CommandName="RebindGrid" CssClass="btnAggiorna">
                                <asp:Localize ID="Localize1" runat="server" Text="<%$ Resources:Labels,Refresh %>" />
                            </asp:LinkButton>
                            <asp:LinkButton ID="btnGestioneBan" runat="server" OnClientClick="manageBans(); return false;" CssClass="btnAggiungi">
                                <asp:Localize ID="Localize2" runat="server" Text="<%$ Resources:,GestisciBan %>" />
                            </asp:LinkButton>
                        </td>
                    </tr>
                </table>
            </CommandItemTemplate>
            <CommandItemStyle Height="25px" />
            <Columns>
                <telerik:GridTemplateColumn HeaderText="<%$ Resources:Grids,Commenti_Articolo %>" DataField="titolo"
                    UniqueName="titolo" AllowFiltering="true" CurrentFilterFunction="Contains" CurrentFilterValue=""
                    ShowFilterIcon="false" SortExpression="titolo" AutoPostBackOnFilter="True" FilterControlWidth="400px">
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lbl_titolo" Text='<%# Eval("titolo") %>' />
                    </ItemTemplate>
                    <ItemStyle Width="500px" />
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn HeaderText="<%$ Resources:Grids,Commenti_Pubblicati %>" UniqueName="pubblicati"
                    AllowFiltering="false">
                    <ItemTemplate>
                        <a href="" onclick='<%# "showPublishedComments(" + Eval("id_articolo").ToString() + "); return false;" %>' class="lblRimbalzi">
                            <asp:Label runat="server" ID="lbl_pubblicati" Text='' /></a>
                    </ItemTemplate>
                    <ItemStyle Width="100px" />
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn HeaderText="<%$ Resources:Grids,Commenti_DaApprovare %>"
                    UniqueName="daapprovare" AllowFiltering="false">
                    <ItemTemplate>
                        <asp:Label runat="server" ID="lbl_da_approvare" Text='' />
                    </ItemTemplate>
                    <ItemStyle Width="100px" />
                </telerik:GridTemplateColumn>
            </Columns>
            <DetailTables>
                <telerik:GridTableView Name="Commenti" runat="server" DataKeyNames="id_commento" AutoGenerateColumns="false"
                    AllowPaging="true" AllowSorting="true" AllowFilteringByColumn="false" PageSize="5"
                    NoMasterRecordsText="<%$ Resources:Labels,NessunDato %>" NoDetailRecordsText="<%$ Resources:Labels,NessunDato %>">
                    <Columns>
                        <telerik:GridTemplateColumn HeaderText="" UniqueName="commento" AllowFiltering="false">
                            <ItemTemplate>
                                <table>
                                    <tr>
                                        <td>
                                            <asp:Label runat="server" Text="<%$ Resources:,ID %>" />
                                        </td>
                                        <td>
                                            <asp:Label runat="server" ID="lbl_id_commento" Text='<%# Eval("id_commento") %>' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label runat="server" Text="<%$ Resources:,Autore %>" />
                                        </td>
                                        <td>
                                            <asp:Label runat="server" ID="lbl_autore" Text='<%# GetCommentAuthor((Commento)Container.DataItem) %>' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label ID="Label1" runat="server" Text="<%$ Resources:,Email %>" />
                                        </td>
                                        <td>
                                            <asp:Label runat="server" ID="Label3" Text='<%# Eval("email") %>' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label runat="server" Text="<%$ Resources:,Data %>"></asp:Label>
                                        </td>
                                        <td>
                                            <asp:Label runat="server" ID="lbl_dataregistrazione" Text='<%# Eval("dataregistrazione","{0:g}") %>' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label runat="server" Text="<%$ Resources:,Oggetto %>" />
                                        </td>
                                        <td>
                                            <asp:Label runat="server" ID="lbl_oggetto" Text='<%# GetCommentSubject(Eval("oggetto").ToString()) %>' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <asp:Label runat="server" Text="<%$ Resources:,Messaggio %>" />
                                        </td>
                                        <td>
                                            <asp:Literal Mode="PassThrough" runat="server" ID="lbl_messaggio" Text='<%# GetCommentBody(Eval("body").ToString()) %>' />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <asp:LinkButton ID="btnApprova" CommandName="ApproveComment" runat="server" Text="<%$ Resources:,Approva %>" CssClass="btnAnnulla_Click" />
                                              
                                            
                                            <asp:LinkButton ID="btnCancella" OnClientClick='<%# GenerateDeleteScript() %>' CommandName="DeleteComment" runat="server" Text="<%$ Resources:Labels,Elimina %>" CssClass="btnElimina" />
                                        </td>
                                    </tr>
                                </table>
                            </ItemTemplate>
                        </telerik:GridTemplateColumn>
                    </Columns>
                </telerik:GridTableView>
            </DetailTables>
            <PagerStyle AlwaysVisible="true" PageSizes="10" />
        </MasterTableView>
    </telerik:RadGrid>

In the backend I have the following code which is executed in Page_Load:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            BindGrid();
    }
 
    private void BindGrid()
    {
        CommentiController controller = new CommentiController();
        grdArticoliCommentabili.DataSource = controller.SelectCommentableArticles("CommentiArticolo");
        grdArticoliCommentabili.DataBind();
    }
 
    private void ReloadCommentsGrid(GridEditableItem item)
    {
        CommentiController controller = new CommentiController();
        var id_articolo = (int)item.OwnerTableView.ParentItem.GetDataKeyValue("id_articolo");
        item.OwnerTableView.DataSource = controller.SelectNonApprovedCommentsByArticle(id_articolo, "Utente");
        item.OwnerTableView.DataBind();
    }
 
    private void LoadCommentsGrid(GridTableView view)
    {
        CommentiController controller = new CommentiController();
        int id_articolo = (int)view.ParentItem.GetDataKeyValue("id_articolo");
        view.DataSource = controller.SelectNonApprovedCommentsByArticle(id_articolo, "Utente");
    }
 
    protected void grdArticoliCommentabili_ItemCommand(object source, GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.RebindGridCommandName || e.CommandName == RadGrid.FilterCommandName)
        {
            BindGrid();
        }
        else if (e.CommandName == "ApproveComment")
        {     
            var item = e.Item as GridEditableItem;
            var id_commento = (int)item.GetDataKeyValue("id_commento");
 
            if (!JPortalUserBag.HasPermission(Entities.Commento, Permissions.Edit, Entities.NoEntityID))
            {
                SetError(GetGlobalString("Errors", "SicurezzaPermessiInsufficentiOperazione"));
                LogManager.WriteWarning(GetLogSubject(), GetGlobalString("Errors", "SicurezzaPermessiInsufficentiOperazione"));
                BindGrid();
                return;
            }
 
            try
            {
                CommentiController controller = new CommentiController();
                var commento = controller.SelectByID(id_commento);
                commento.approvato = true;
 
                var parent_item = item.OwnerTableView.ParentItem;
 
                var lbl_pubblicati = (parent_item["pubblicati"].FindControl("lbl_pubblicati") as Label);
                var lbl_da_approvare = (parent_item["daapprovare"].FindControl("lbl_da_approvare") as Label);
 
                int parent_pubblicati = Convert.ToInt32(lbl_pubblicati.Text);
                int parent_daapprovare = Convert.ToInt32(lbl_da_approvare.Text);
 
                parent_pubblicati++;
                parent_daapprovare--;
 
                lbl_pubblicati.Text = parent_pubblicati.ToString();
                lbl_da_approvare.Text = parent_daapprovare.ToString();
 
                controller.Update(commento, false);
                ReloadCommentsGrid(item);
 
                LogManager.WriteMessage(GetLogSubject(), GetGlobalString("Messages", "CommentoApprovazione").Arguments(id_commento.ToString()));
                SetMessage(GetGlobalString("Messages", "CommentoApprovazione").Arguments(id_commento.ToString()));
            }
            catch (Exception)
            {
                LogManager.WriteError(GetLogSubject(), GetGlobalString("Errors", "CommentoApprovazione").Arguments(id_commento.ToString()));
                SetError(GetGlobalString("Errors", "CommentoApprovazione").Arguments(id_commento.ToString()));
                throw;
            }
        }
        else if (e.CommandName == "DeleteComment")
        {
            var item = e.Item as GridEditableItem;
            var id_commento = (int)item.GetDataKeyValue("id_commento");
 
            if (!JPortalUserBag.HasPermission(Entities.Commento, Permissions.Delete, Entities.NoEntityID))
            {
                SetError(GetGlobalString("Errors", "SicurezzaPermessiInsufficentiOperazione"));
                LogManager.WriteWarning(GetLogSubject(), GetGlobalString("Errors", "SicurezzaPermessiInsufficentiOperazione"));
                BindGrid();
                return;
            }
 
            try
            {
                CommentiController controller = new CommentiController();
                var commento = controller.SelectByID(id_commento);
 
                var parent_item = item.OwnerTableView.ParentItem;
                var lbl_da_approvare = (parent_item["daapprovare"].FindControl("lbl_da_approvare") as Label);
                int parent_daapprovare = Convert.ToInt32(lbl_da_approvare.Text);
 
                lbl_da_approvare.Text = (--parent_daapprovare).ToString();
 
                controller.Delete(commento, false);
                ReloadCommentsGrid(item);
 
                LogManager.WriteMessage(GetLogSubject(), GetGlobalString("Messages", "CommentoEliminazione").Arguments(id_commento.ToString()));
                SetMessage(GetGlobalString("Messages", "CommentoEliminazione").Arguments(id_commento.ToString()));
 
            }
            catch (Exception)
            {
                LogManager.WriteError(GetLogSubject(), GetGlobalString("Errors", "CommentoEliminazione").Arguments(id_commento.ToString()));
                SetError(GetGlobalString("Errors", "CommentoEliminazione").Arguments(id_commento.ToString()));
                throw;
            }
        }
    }
 
    protected string GetCommentSubject(string input)
    {
        if (String.IsNullOrEmpty(input))
        {
            return GetLocalString("CommentoOggettoEliminato");
        }
        else
        {
            return input;
        }
    }
 
    protected string GetCommentBody(string input)
    {
        if (String.IsNullOrEmpty(input))
        {
            return GetLocalString("CommentoEliminato");
        }
        else
        {
            return input;
        }
    }
 
    protected string GetCommentAuthor(Commento comm)
    {
        if (comm.nome != null && comm.cognome != null)
            return String.Concat(comm.nome, " ", comm.cognome);
        else
            return comm.Utente != null ? comm.Utente.login : String.Empty;
    }
 
    protected string GenerateDeleteScript()
    {
        return "return showDoublePrompt('{0}',null);".Arguments(GetJSString(GetGlobalString("Messages", "MessaggioEliminazione")));
    }
 
    private string GetJSString(string input)
    {
        return input.Replace("'", "\'");
    }
 
    protected void grdArticoliCommentabili_DetailTableDataBind(object source, GridDetailTableDataBindEventArgs e)
    {
        LoadCommentsGrid(e.DetailTableView);
    }
 
    protected void grdArticoliCommentabili_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridEditableItem)
        {
            var item = e.Item as GridEditableItem;
            var articolo = item.DataItem as Articolo;
            if (item.OwnerTableView.Name == "Commenti") return;
 
            var lbl_pubblicati = (item["pubblicati"].FindControl("lbl_pubblicati") as Label);
            var lbl_da_approvare = (item["daapprovare"].FindControl("lbl_da_approvare") as Label);
 
            var totale_commenti = articolo.CommentiArticolo.Where(a => a.approvato == true).Count();
            var da_approvare = articolo.CommentiArticolo.Where(a => a.approvato == false).Count();
 
            lbl_pubblicati.Text = totale_commenti.ToString();
            lbl_da_approvare.Text = da_approvare.ToString();
        }
    }
 
    protected void grdArticoliCommentabili_PageIndexChanged(object source, GridPageChangedEventArgs e)
    {
        BindGrid();
    }
 
    protected void grdArticoliCommentabili_PageSizeChanged(object source, GridPageSizeChangedEventArgs e)
    {
        BindGrid();
    }

The problem is that when "DataBind" method is executed in "BindGrid" (called by Page_Load) also the PageSizeChanged event is raised, which, in turn causes the "BindGrid" method to be recalled, which again, raises the PageSizeChanged event and so on... until the StackOverflowException is raised... Can I know why "PageSizeChanged" is raised when I call "DataBind"?

* UPDATE * 
I want to add that the PageSizeChanged event is raised not one time, but five: equal to the number of rows in the MasterTableView.

Thank you!

1 Answer, 1 is accepted

Sort by
0
Andrey
Telerik team
answered on 10 Apr 2013, 07:48 AM
Hello,

The problem that you are experiencing comes from the fact that you are using DataBind() method to bind the data to grid. As this help article says you should not use DataBind() method when you are using paging, grouping, filtering, or sorting.

Try to use NeedDataSource and you should not have problems.

Greetings,
Andrey
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
Tags
Grid
Asked by
massimo mannoni
Top achievements
Rank 1
Answers by
Andrey
Telerik team
Share this question
or