Changing Page Size Throws NullReferenceException

17 posts, 0 answers
  1. Geoff
    Geoff avatar
    21 posts
    Member since:
    Jun 2010

    Posted 04 Apr 2012 Link to this post

    Hello,

    I have a grid whose items I am always keeping in edit mode. But I've noticed that certain operations (such as column sorting, for example), causes the edit items to revert back to browse mode. To avoid this, I handle the grid commands explicitly, and set the grid back to edit mode once the command has executed.

    Here is my declaration of the grid:
    <telerik:RadGrid ID="dtgBuildingSizes" runat="server" AllowPaging="true" AllowSorting="true" AllowFilteringByColumn="true" ShowFooter="true"
        AutoGenerateColumns="false" EnableHeaderContextMenu="true" EnableHeaderContextFilterMenu="true" PageSize="5"
        AllowMultiRowEdit="true" Width="100%" EnableLinqExpressions="false"
        OnNeedDataSource="dtgBuildingSizes_NeedDataSource" OnItemDataBound="dtgBuildingSizes_ItemDataBound"
        OnPreRender="dtgBuildingSizes_PreRender" OnItemCommand="dtgBuildingSizes_ItemCommand">
        <MasterTableView DataKeyNames="Id" EditMode="InPlace" IsFilterItemExpanded="false">
            <Columns>
                <telerik:GridBoundColumn UniqueName="SizeTypeDescr" DataField="SizeTypeDescr" HeaderText="<%$ Resources: SizeType %>" ReadOnly="true" />
                <telerik:GridNumericColumn UniqueName="Size" DataField="Size" DataType="System.Decimal" ItemStyle-HorizontalAlign="Right"
                    HeaderStyle-HorizontalAlign="Right" HeaderText="<%$ Resources:RpaControlCaptions, lblSize %>" />
                <telerik:GridButtonColumn UniqueName="Delete" CommandName="Delete" ButtonCssClass="rgDel" ButtonType="LinkButton"
                        ItemStyle-HorizontalAlign="Right" ShowInEditForm="true"
                        ConfirmText="<%$ Resources: AreYouSureYouWantToDeleteThisSize %>" />
            </Columns>
        </MasterTableView>
    </telerik:RadGrid>

    And here is the relevant C# code:
    protected void dtgBuildingSizes_PreRender(object sender, EventArgs e)
    {
        //initially set appropriate size grid rows to edit mode
        if (!IsPostBack)
            dtgBuildingSizes.SetSizesGridToEditMode();
    }
     
    protected void dtgBuildingSizes_NeedDataSource(object sender, TelerikUI.GridNeedDataSourceEventArgs e)
    {
        var dataSource = ((BuildingEntity)CurrentBusinessEntity).Sizes;
        dtgBuildingSizes.DataSource = dataSource;
        dtgBuildingSizes.VirtualItemCount = dataSource.Count;
    }
     
    protected void dtgBuildingSizes_ItemDataBound(object sender, TelerikUI.GridItemEventArgs e)
    {
        if (e.Item is TelerikUI.GridDataItem)
        {
            TelerikUI.GridDataItem dataItem = (TelerikUI.GridDataItem)e.Item;
     
            //show/hide delete button based on availability for the size type
            BuildingSizeEntity entity = (BuildingSizeEntity)dataItem.DataItem;
            dataItem["Delete"].Controls[0].Visible = entity.IsDeletable;
        }
    }
     
    protected void dtgBuildingSizes_ItemCommand(object sender, TelerikUI.GridCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case RadGrid.DeleteCommandName:
                if (e.Item is TelerikUI.GridDataItem)
                {
                    //remove the selected entity from the collection
                    TelerikUI.GridDataItem dataItem = (TelerikUI.GridDataItem)e.Item;
                    BuildingSizeEntity deletedEntity = GetSizeEntityForGridItem(dataItem);
                    ((BuildingEntity)CurrentBusinessEntity).Sizes.Remove(deletedEntity);
                }
                break;
            default:
                if (ControlsUtil.IsRebindNeededForRadGridCommand(e.CommandName))
                {
                    //save previous edits before rebind
                    PostAllSizeData();
     
                    //execute command and place grid back into edit mode
                    e.ExecuteCommand(sender);
                    dtgBuildingSizes.SetSizesGridToEditMode();
     
                    e.Canceled = true//no further processing required
                }
                break;
        }
    }
     
    public static bool IsRebindNeededForRadGridCommand(string commandName)
    {
        switch (commandName)
        {
            // Editing
            case RadGrid.CancelAllCommandName:
            case RadGrid.CancelCommandName:
            case RadGrid.DeleteCommandName:
            case RadGrid.DeleteSelectedCommandName:
            case RadGrid.EditAllCommandName:
            case RadGrid.EditCommandName:
            case RadGrid.EditSelectedCommandName:
            case RadGrid.InitInsertCommandName:
            case RadGrid.PerformInsertCommandName:
            case RadGrid.UpdateCommandName:
            case RadGrid.UpdateEditedCommandName:
     
            // Filtering
            case RadGrid.ClearFilterCommandName:
            case RadGrid.FilterCommandName:
            case RadGrid.HeaderContextMenuFilterCommandName:
     
            // Paging
            case "ChangePageSize":
            case RadGrid.FirstPageCommandArgument:
            case RadGrid.LastPageCommandArgument:
            case RadGrid.NextPageCommandArgument:
            case RadGrid.PageCommandName:
            case RadGrid.PrevPageCommandArgument:
     
            // Sorting
            case RadGrid.ClearSortCommandName:
            case RadGrid.SortCommandName:
     
            // Misc.
            case RadGrid.ExpandCollapseCommandName:
            case RadGrid.RebindGridCommandName:
                return true;
            default:
                return false;   //all others do not implicitly call rebind
        }
    }
     
    public static void SetSizesGridToEditMode(this RadGrid grid)
    {
        if (grid != null)
        {
            SizeEntity size;
            foreach (GridDataItem dataItem in grid.Items)
            {
                size = dataItem.DataItem as SizeEntity;
                if (size != null)
                    dataItem.Edit = !size.IsReadOnly;   //only set editable items to edit mode
            }
     
            grid.Rebind();
        }
    }

    This works perfectly for all grid commands with the exception of the command to change the page size. When I call ExecuteCommand( ) for the GridPageSizeChangedEventArgs object (e) passed in, it throws a NullReferenceException, causing the action to fail.

    How can I execute the page size event and keep my grid items always in edit mode? I realize that I can workaround this by removing the "default" case from the ItemCommand event handler and by removing the "if (!IsPostBack)" check from the grid's PreRender event handler, but I don't want to rebind the grid twice (first for the initial items, then again for setting each item to edit mode) every time the grid has to be rendered. I've noticed that this approach significantly slows down performance, especially when there are many grids being rebound several times each for each postback.

    Is there a way I can get around this exception? Or alternatively, is there another way to ensure that the grid items are always in edit mode that doesn't require binding the grid twice?

    Thanks!
    Geoff
  2. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 05 Apr 2012 Link to this post

    Hi,

    Please try the following code to put grid items in edit mode and check whether it solves the issue.

    C#:
    protected void Page_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < dtgBuildingSizes.PageSize; i++)
        {
            dtgBuildingSizes.EditIndexes.Add(i);
        }
    }

    Thanks,
    Shinu
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Geoff
    Geoff avatar
    21 posts
    Member since:
    Jun 2010

    Posted 05 Apr 2012 Link to this post

    Hi Shinu,

    Thank you for your quick reply. Unfortunately, your suggestion did not work for me. It places the items in edit mode on the initial page load, but it does not work when paging. The paging works as expected, but the items not in the original page do not appear in edit mode. Those items also do not appear in edit mode when sorting. I suspect this is the case because the Page_Load event is handled before the ItemCommand event of the grid.

    Is there any other way?

    Also, I'd like to know about the ExecuteCommand exception in case I will ever need to use that for a handling a page size changed command. Is this a bug, or am I missing something?

    Thanks,
    Geoff
  5. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 09 Apr 2012 Link to this post

    Hello Geoff,

    If you want to persist the items in edit mode while paging and sorting, try the following code in PreRender event.
    C#:
    protected void RadGrid1_PreRender(object sender, EventArgs e)
    {
     for (int count = 0; count < RadGrid1.PageSize; count++)
     {
        RadGrid1.EditIndexes.Add(count);
     }
      RadGrid1.Rebind();
    }

    Thanks,
    Shinu.
  6. Geoff
    Geoff avatar
    21 posts
    Member since:
    Jun 2010

    Posted 09 Apr 2012 Link to this post

    Shinu,

    How is that any better than what I had in the first place? I said I didn't want to rebind the grid twice and that's exactly what your solution requires.

    And you also didn't address the other part of the issue regarding the exception that is thrown.

    I appreciate that you trying to help, but you would be a great deal more helpful if you would actually read my replies before responding to them.

    Geoff
  7. Pavlina
    Admin
    Pavlina avatar
    6084 posts

    Posted 09 Apr 2012 Link to this post

    Hello,

    Please go through the help article below which shows how to put items in edit mode without additional rebind:
    http://www.telerik.com/help/aspnet-ajax/grid-put-all-items-in-edit-mode-no-additional-rebind.html

    and let me know if it works for you.

    All the best,
    Pavlina
    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.
  8. Geoff
    Geoff avatar
    21 posts
    Member since:
    Jun 2010

    Posted 11 Apr 2012 Link to this post

    Hi Pavlina,

    I tried you suggestion and combining what was described in the help article with some of what I already had got me what I needed, thanks! But I have a question on the article you posted. In the foreach block, there is a type check to determine if item is a GridEditableItem type. But the Items property of the MasterTableView returns a collection of GridDataItem objects and GridDataItem descends directly from GridEditableItem. Therefore, the item will always be of type GridEditableItem so the type check is not necessary. Is there a specific reason why the check is there?

    And secondly, I'd still like to see the issue regarding the null reference exception being addressed. Is this a reproducible bug on your end?

    Thanks,
    Geoff
  9. Geoff
    Geoff avatar
    21 posts
    Member since:
    Jun 2010

    Posted 11 Apr 2012 Link to this post

    Pavlina,

    Actually I take back the previous post. It turns out that what's described in the help article does not help after all. The issue is that it doesn't work when sorting or paging. After sorting or paging, the items do not remain in edit mode. This likely happens with filtering as well, though I didn't test that.

    Is there any other way to achieve my request that will also work with all grid commands (sorting, paging, etc.)?

    Geoff
  10. Pavlina
    Admin
    Pavlina avatar
    6084 posts

    Posted 17 Apr 2012 Link to this post

    Hello Geoff,

    Usually the edit mode of the items is not kept when sorting, filtering or changing the page( look at this demo). I recommend that you save it using an approach similar to the approach in the Persisting the selected rows server-side on sorting/paging/filtering/grouping help topic.

    Regards,
    Pavlina
    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.
  11. Geoff
    Geoff avatar
    21 posts
    Member since:
    Jun 2010

    Posted 17 Apr 2012 Link to this post

    Hi Pavlina,

    Thank you for the links, but they are no better than what I already have. What I do have seems to work in every scenario except for changing the page size.

    So, for the FIFTH time I will ask again:
    I'd still like to see the issue regarding the null reference exception being addressed. Is this a reproducible bug on your end?
  12. Pavlina
    Admin
    Pavlina avatar
    6084 posts

    Posted 20 Apr 2012 Link to this post

    Hello Geoff,

    Can you please try to use the code snippet below for putting grid items in edit mode and let us know if you still receive null reference exception while changing the page size?
    protected void RadGrid1_PreRender(object sender, System.EventArgs e)
        {
            foreach (GridDataItem item in this.RadGrid1.Items)
            {
                item.Edit = true;
            }
            RadGrid1.Rebind();
        }

    In case the issue still persists I will ask you to open a formal support ticket and send us a sample runnable application where this problem ca be replicated. We will debug it locally and get back to you with our findings.

    Greetings,
    Pavlina
    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.
  13. Geoff
    Geoff avatar
    21 posts
    Member since:
    Jun 2010

    Posted 23 Apr 2012 Link to this post

    Hi Pavlina,

    The code snippet you provided does not produce the exception. The call to ExecuteCommand is what produces the exception (see my original post). From what I can tell, the exception is thrown only when changing the page size.

    Thanks,
    Geoff
  14. Pavlina
    Admin
    Pavlina avatar
    6084 posts

    Posted 26 Apr 2012 Link to this post

    Hello Geoff,

    At this point to be able to assist you further we will need to replicate the described issue locally. Otherwise it will be hard to determine what is causing it. Therefore, I will ask you to isolate the problem in a sample project and send it to us via a formal support ticket. Thank you in advance for your cooperation.

    Regards,
    Pavlina
    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.
  15. Anthony
    Anthony avatar
    3 posts
    Member since:
    Aug 2008

    Posted 16 May 2012 Link to this post

    Hi Geoff,

    I have similar situation with my application except I don't allow for users to change page size so in this example, i don't have to worry about it.  However, i was looking at your code snippets and I was curious how you are handling the PostAllSizeData() for different e.Item type (ie. GridHeaderItem, etc).

    Could you share your code regarding PostAllSizeData()? Obviously the specifics of commiting to database will be very different but I'm just curious of how you managed to get and persist data on different events (ie. sort).

    Thanks!
  16. Geoff
    Geoff avatar
    21 posts
    Member since:
    Jun 2010

    Posted 21 May 2012 Link to this post

    Hi Anthony,

    Just for clarification, the posting of data I do here is just to ensure that all of the user's changes are made to the business objects before the rebind so that their changes still appear afterward.

    private void PostAllSizeData()
    {
        foreach (TelerikUI.GridDataItem editItem in dtgBuildingSizes.EditItems)
            PostSizeData(editItem,
                ((BuildingEntity)CurrentBusinessEntity).Sizes.GetById(Convert.ToInt32(editItem.GetDataKeyValue("Id"))));
    }
     
    private void PostSizeData(TelerikUI.GridDataItem dataItem, BuildingSizeEntity entity)
    {
        dataItem.UpdateValues(entity);
    }

    The user actually persists their changes to the database elsewhere.

    Hope this helps!

    Geoff
  17. Kevin
    Kevin avatar
    1 posts
    Member since:
    Mar 2015

    Posted 12 Mar 2015 Link to this post

    I know this in an old thread, but I am able to reproduce this issue. I came across the error in a different way that may be more helpful for debugging the issue. On the PageSizeChanged event, e.Item is null. The PageIndexChanged and SortCommand events both have e.Item populated.

    Do I need to provide a sample project?
  18. Pavlina
    Admin
    Pavlina avatar
    6084 posts

    Posted 16 Mar 2015 Link to this post

    Hi Kevin,

    Could you confirm that this problem persists with the latest Q1 2015 version of Telerik.UI for ASP.NET AJAX?

    Regards,
    Pavlina
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017