ArgumentOutOfRangeException in Telerik.Web.UI.GridEditableItem.GetDataKeyValue(String keyName) only on last page

9 posts, 0 answers
  1. Rob
    Rob avatar
    43 posts
    Member since:
    Aug 2010

    Posted 10 Nov 2015 Link to this post

    I have a RadGrid and a corresponding edit form, then I have a template column with a button like this:

    <telerik:GridTemplateColumn UniqueName="EditRow" AllowFiltering="False"
        AllowSorting="False" FilterControlAltText="Filter EditRow column">
        <ItemTemplate>
            <asp:ImageButton ID="EditLink" runat="server" ImageUrl="~/IMAGES/Edit16.png" ToolTip="Edit" />
        </ItemTemplate>
        <HeaderStyle Width="32px" />
    </telerik:GridTemplateColumn>

    Then I bind a custom handler in the code behind:

    ImageButton editLink = (ImageButton)e.Item.FindControl("EditLink");
    editLink.CommandArgument = item.GetDataKeyValue("AncilliaryID").ToString() + "," + item.GetDataKeyValue("ID").ToString();
    editLink.Command += new CommandEventHandler(EditCommand);

    The grid has 10 pages of data in it, 50 rows per page, and this all works perfectly on the first nine pages.  However clicking the edit button on the 10th page leads to this error:

    [ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index]
       System.Collections.ArrayList.get_Item(Int32 index) +10705936
       Telerik.Web.UI.GridEditableItem.GetDataKeyValue(String keyName) +48
       Telerik.Web.UI.RadGrid.DescribeProperties(IScriptDescriptor descriptor) +5760
       ...

    This error occurs even if I comment out all the event binding code.  Something is happening in the RadGrid code for the last page of the grid only.  What sort of thing could be causing this?  I am assuming there is something basic I have overlooked in the properties or the binding of the grid that would only cause an issue on the last (non-full) page of the displayed grid but I have no idea how I can work out what that would be.

  2. Rob
    Rob avatar
    43 posts
    Member since:
    Aug 2010

    Posted 12 Nov 2015 Link to this post

    Turns out that this error happens for any postback fired on the page containing the grid if the grid is on the last page of results.  Everything works perfectly on the other 47 pages.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Kostadin
    Admin
    Kostadin avatar
    1708 posts

    Posted 13 Nov 2015 Link to this post

    Hello Rob,

    Could you please provide the entire grid declaration and all the related code behind? I assume that you try to access an item from a collection but you exceed its length. Nevertheless, without your code it will be hard to pinpoint the exact reason for this issue.

    Regards,
    Kostadin
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
  5. Rob
    Rob avatar
    43 posts
    Member since:
    Aug 2010

    Posted 13 Nov 2015 in reply to Kostadin Link to this post

    <telerik:RadGrid RenderMode="Lightweight" ID="ServiceWorkTypeGrid" runat="server"
        OnPreRender="ServiceWorkTypeGrid_PreRender" AllowFiltering="True"
        AllowFilteringByColumn="True" OnItemDataBound="ServiceWorkTypeGrid_ItemDataBound"
        PageSize="25" AllowPaging="True" VirtualItemCount="0"
        AllowMultiRowSelection="True" OnItemCreated="ServiceWorkTypeGrid_ItemCreated"
        AllowSorting="True" OnColumnCreated="ServiceWorkTypeGrid_ColumnCreated"
        ShowGroupPanel="True" OnNeedDataSource="ServiceWorkTypeGrid_NeedDataSource"
        GroupPanelPosition="Top" meta:resourcekey="ServiceWorkTypeGridResource1"
        ResolvedRenderMode="Lightweight">
        <GroupingSettings CaseSensitive="False" />
        <PagerStyle Mode="Advanced" Position="Bottom"></PagerStyle>
        <ClientSettings AllowColumnsReorder="False" EnablePostBackOnRowClick="False">
            <Selecting AllowRowSelect="False" />
            <Scrolling AllowScroll="True" UseStaticHeaders="True" />
        </ClientSettings>
        <MasterTableView AutoGenerateColumns="False" TableLayout="Fixed" PagerStyle-Mode="Advanced"
            EnableViewState="true" EnableColumnsViewState="true"
            DataKeyNames="ServiceWorkTypeID,ServiceID,WorkTypeID,ServiceGroupID,Messages,Instructions"
            ClientDataKeyNames="ServiceWorkTypeID,ServiceID,WorkTypeID,ServiceGroupID">
            <Columns>
                <telerik:GridTemplateColumn UniqueName="EditRow" AllowFiltering="False"
                    AllowSorting="False" FilterControlAltText="Filter EditRow column"
                    meta:resourcekey="GridTemplateColumnResource1">
                    <ItemTemplate>
                        <asp:ImageButton ID="EditLink" runat="server" ImageUrl="~/IMAGES/Edit16.png"
                            meta:resourceKey="EditLinkResource1" ToolTip="Edit" />
                    </ItemTemplate>
                    <HeaderStyle Width="32px" />
                </telerik:GridTemplateColumn>
                <telerik:GridTemplateColumn UniqueName="DeleteRow" AllowFiltering="False"
                    AllowSorting="False" FilterControlAltText="Filter DeleteRow column"
                    meta:resourcekey="GridTemplateColumnResource2">
                    <ItemTemplate>
                        <asp:ImageButton ID="DeleteLink" runat="server"
                            ImageUrl="~/IMAGES/Delete16.png" meta:resourceKey="DeleteLinkResource1"
                            ToolTip="Delete" />
                    </ItemTemplate>
                    <HeaderStyle Width="32px" />
                </telerik:GridTemplateColumn>
                <telerik:GridBoundColumn UniqueName="ServiceGroup" DataField="ServiceGroupName"
                    HeaderText="Service Group" FilterControlWidth="66%"
                    FilterControlAltText="Filter ServiceGroup column"
                    meta:resourcekey="GridBoundColumnResourceServiceGroup">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="Service" DataField="ServiceName"
                    HeaderText="Service" FilterControlWidth="66%"
                    FilterControlAltText="Filter Service column"
                    meta:resourcekey="GridBoundColumnResourceService">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="WorkType" DataField="WorkTypeName"
                    HeaderText="Work Type" FilterControlWidth="66%"
                    FilterControlAltText="Filter WorkType column"
                    meta:resourcekey="GridBoundColumnResourceWorkType">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="Priority" DataField="DefPriorityName"
                    HeaderText="Priority" FilterControlWidth="66%"
                    FilterControlAltText="Filter Priority column"
                    meta:resourcekey="GridBoundColumnResourcePriority">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="Agent" DataField="DefAgentName"
                    HeaderText="Agent" FilterControlWidth="66%"
                    FilterControlAltText="Filter Agent column"
                    meta:resourcekey="GridBoundColumnResourceAgent">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="ExportValue" DataField="ExportValue"
                    HeaderText="Export Value" FilterControlWidth="66%"
                    FilterControlAltText="Filter ExportValue column"
                    meta:resourcekey="GridBoundColumnResourceExportValue">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="KPIReference" DataField="KPIReferenceName"
                    HeaderText="KPI Reference" FilterControlWidth="66%"
                    FilterControlAltText="Filter KPIReference column"
                    meta:resourcekey="GridBoundColumnResourceKPIReference">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="SystemMetaDataTags"
                    DataField="SystemMetaDataTags" HeaderText="System Meta Data Tags"
                    FilterControlWidth="66%"
                    FilterControlAltText="Filter SystemMetaDataTags column"
                    meta:resourcekey="GridBoundColumnResourceSystemMetaDataTags">
                    <HeaderStyle Width="140px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="CostCode" DataField="CostCodeName"
                    HeaderText="Cost Code" FilterControlWidth="66%"
                    FilterControlAltText="Filter CostCode column"
                    meta:resourcekey="GridBoundColumnResourceCostCode">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridTemplateColumn UniqueName="EstimatedCost" DataField="EstimatedCost"
                    HeaderText="Estimated Cost" FilterControlWidth="66%" DataType="System.Decimal"
                    FilterControlAltText="Filter EstimatedCost column"
                    meta:resourcekey="GridTemplateColumnResourceEstimatedCost">
                    <ItemTemplate>
                        <asp:Label ID="lblEstimatedCost" runat="server" Text='<%# QFM.Services.Common.Currency.FormatForCulture((decimal?)DataBinder.Eval(Container.DataItem, "EstimatedCost"), UserContext) %>'></asp:Label>
                    </ItemTemplate>
                    <HeaderStyle Width="120px" />
                </telerik:GridTemplateColumn>
                <telerik:GridBoundColumn UniqueName="PotentialLiability"
                    DataField="PotentialLiabilityName" HeaderText="Potential Liability"
                    FilterControlWidth="66%"
                    FilterControlAltText="Filter PotentialLiability column"
                    meta:resourcekey="GridBoundColumnResourcePotentialLiability">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="Messages"
                    DataField="Messages" HeaderText="Messages"
                    AllowFiltering="false"
                    meta:resourcekey="GridBoundColumnResourceMessages">
                    <HeaderStyle Width="150px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="ShowMessages"
                    DataField="ShowMessages" HeaderText="Show Messages"
                    AllowFiltering="false"
                    meta:resourcekey="GridBoundColumnResourceShowMessages">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="Instructions"
                    DataField="Instructions" HeaderText="Instructions"
                    AllowFiltering="false"
                    meta:resourcekey="GridBoundColumnResourceInstructions">
                    <HeaderStyle Width="150px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="EventTypeName" DataField="EventTypeName"
                    HeaderText="Task Type" FilterControlWidth="66%"
                    FilterControlAltText="Filter TaskType column"
                    meta:resourcekey="GridBoundColumnResourceEventSubType">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="WFTag" DataField="WFTag"
                    HeaderText="Workflow" FilterControlWidth="66%"
                    FilterControlAltText="Filter Workflow column"
                    meta:resourcekey="GridBoundColumnResourceWFTag">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="WFInitializationEvent" DataField="WFInitializationEvent"
                    HeaderText="Initial Action" FilterControlWidth="66%"
                    FilterControlAltText="Filter Initial Action column"
                    meta:resourcekey="GridBoundColumnResourceWFInitializationEvent">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="ProjectGroup" DataField="TaskGroup"
                    HeaderText="Task Group" FilterControlWidth="66%"
                    FilterControlAltText="Filter ProjectGroup column"
                    meta:resourcekey="GridBoundColumnResourceProjectGroup">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="TaskSequence" DataField="TaskSequence"
                    HeaderText="Task Sequence" FilterControlWidth="66%"
                    FilterControlAltText="Filter TaskSequence column"
                    meta:resourcekey="GridBoundColumnResource4">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="StartDependancyOnWorkTypeName" DataField="StartDependancyOnWorkTypeName"
                    HeaderText="Preceding Task" FilterControlWidth="66%"
                    FilterControlAltText="Filter StartDependancy column"
                    meta:resourcekey="GridBoundColumnResourceStartDependancy">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn UniqueName="WFStartDependancyEvent" DataField="WFStartDependancyEvent"
                    HeaderText="Triggered Action" FilterControlWidth="66%"
                    FilterControlAltText="Filter WFStartDependancy column"
                    meta:resourcekey="GridBoundColumnResourceWFStartDependancy">
                    <HeaderStyle Width="120px" />
                </telerik:GridBoundColumn>
            </Columns>
        </MasterTableView>
        <FilterMenu RenderMode="Lightweight">
        </FilterMenu>
        <HeaderContextMenu CssClass="GridContextMenu GridContextMenu_Default"
            RenderMode="Lightweight">
        </HeaderContextMenu>
    </telerik:RadGrid>

     

    void LoadGrid()
    {
        ServiceWorkTypeGrid.DataSource = null;
        ServiceWorkTypeGrid.Rebind();
    }
     
    protected void ServiceWorkTypeGrid_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        var swt = QFM.Services.Events.Reference.ServiceWorkTypes.LoadAll(null, null, UserContext);
        var sorted = swt.Children.OrderBy(c => c.ServiceGroupName).ThenBy(n => n.ServiceName).ThenBy(t => t.TaskGroup).ThenBy(s => s.TaskSequence);
        ServiceWorkTypeGrid.DataSource = sorted;
        ServiceWorkTypeGrid.VirtualItemCount = sorted.Count();
        ServiceWorkTypeGrid.CurrentPageIndex = ServiceWorkTypeGrid.MasterTableView.CurrentPageIndex;
    }
     
    protected void ServiceWorkTypeGrid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        Telerik.Web.UI.GridDataItem dataBoundItem = e.Item as Telerik.Web.UI.GridDataItem;
        if (dataBoundItem != null)
        {
            foreach (Telerik.Web.UI.GridColumn gc in ServiceWorkTypeGrid.MasterTableView.RenderColumns)
            {
                switch (gc.UniqueName)
                {
                    case "Messages":
                        var fullMessages = dataBoundItem["Messages"].Text;
                        var shortMsg = "<div  onclick=\"showSWTText('" + Server.HtmlEncode(fullMessages) + "','Messages');return false;\" title=\"" + GetLocalResourceObject(QFMEntities.eMessageCode.GenClickToSelect.ToString()) + "\">" + TruncateTag(dataBoundItem["Messages"].Text, 100) + "</div>";
                        dataBoundItem["Messages"].Text = "<div  onclick=\"showSWTText('" + Server.HtmlEncode(fullMessages) + "','Messages');return false;\" title=\"" + GetLocalResourceObject(QFMEntities.eMessageCode.GenClickToSelect.ToString()) + "\">" + TruncateTag(fullMessages, 100) + "</div>";
                        break;
                    case "Instructions":
                        var fullInstructions = dataBoundItem["Instructions"].Text;
                        dataBoundItem["Instructions"].Text = "<div  onclick=\"showSWTText('" + Server.HtmlEncode(fullInstructions) + "','Instructions');return false;\" title=\"" + GetLocalResourceObject(QFMEntities.eMessageCode.GenClickToSelect.ToString()) + "\">" + TruncateTag(fullInstructions, 100) + "</div>";
                        break;
                }
            }
        }
    }
     
    private string TruncateTag(string text, int? length)
    {
        return string.Format("<div class='ellipsis'>{0}</div>", text).Truncate(length.GetValueOrDefault(2000), "...");
    }

    protected void ServiceWorkTypeGrid_PreRender(object sender, EventArgs e)
    {
     
    }
     
    protected void ServiceWorkTypeGrid_ColumnCreated(object sender, Telerik.Web.UI.GridColumnCreatedEventArgs e)
    {
     
    }
     
    protected void ServiceWorkTypeGrid_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is Telerik.Web.UI.GridDataItem && !(e.Item is Telerik.Web.UI.GridDataInsertItem))
        {
            Telerik.Web.UI.GridDataItem item = (Telerik.Web.UI.GridDataItem)e.Item;
            try
            {
                ImageButton editLink = (ImageButton)e.Item.FindControl("EditLink");
                editLink.CommandArgument = item.GetDataKeyValue("ServiceWorkTypeID").ToString() + "," + item.GetDataKeyValue("ServiceID").ToString();
                editLink.Command += new CommandEventHandler(EditCommand);
            }
            catch (Exception) { }
     
            try
            {
                ImageButton deleteLink = (ImageButton)e.Item.FindControl("DeleteLink");
                deleteLink.CommandArgument = item.GetDataKeyValue("ServiceWorkTypeID").ToString();
                deleteLink.Command += new CommandEventHandler(DeleteCommand);
            }
            catch (Exception) { }
        }
    }
     
    void EditCommand(Object sender, CommandEventArgs e)
    {
        string[] args = new string[2];
        args = e.CommandArgument.ToString().Split(',');
        int ServiceWorkTypeID = System.Convert.ToInt32(args[0]);
        int ServiceID = System.Convert.ToInt32(args[1]);
        ucEditServiceWorkType1.PersistenceMode = App_Common_UserControls_DataMaintenance_ucEditServiceWorkType.ePersistenceMode.SelfUpdate;
        ucEditServiceWorkType1.DisplayMode = App_Common_UserControls_DataMaintenance_ucEditServiceWorkType.eDisplayMode.Edit;
        ucEditServiceWorkType1.SetEditVisible(true);
        ucEditServiceWorkType1.InitData(ServiceWorkTypeID, ServiceID);
        if (e is Telerik.Web.UI.GridCommandEventArgs)
        {
            ((Telerik.Web.UI.GridCommandEventArgs)e).Canceled = true;
        }
     
    }
     
    void DeleteCommand(Object sender, CommandEventArgs e)
    {
        int ServiceWorkTypeID = System.Convert.ToInt32(e.CommandArgument);
        var swti = new QFMEntities.Reference.ServiceWorkTypeLinkInfo();
        swti.ServiceWorkTypeID = ServiceWorkTypeID;
        try
        {
            QFM.Services.Events.Reference.ServiceWorkTypes.Delete(swti, UserContext);
            MessageBox1.Message(new QFMEntities.WarningInfo() { MessageCode = QFMEntities.eMessageCode.GenRemoveX, Level = QFMEntities.eWarningLevel.Information, Args = new string[] { "ServiceWorkType" } });
        }
        catch (Exception ex)
        {
            MessageBox1.Message(ex);
            new QFM.Services.Workflow.Alarm().Create("GeneralReferenceData:" + this.ControlName + "_" + (ex.InnerException != null ? ex.InnerException.GetType().Name : ex.GetType().Name),
                                                       QFMEntities.General.Alarms.Alarm.eCategory.UnexpectedException, new QFMEntities.WarningInfo(ex, QFMEntities.eWarningLevel.Exception), UserContext);
        }
        LoadGrid();
    }

  6. Kostadin
    Admin
    Kostadin avatar
    1708 posts

    Posted 18 Nov 2015 Link to this post

    Hi Rob,

    I assume the cause for this issue is the code in ItemCreated event handler. Generally you need to access the cell first and then access the control in it. More information could be found in the following help article.
    Another possible reason for this error is the custom paging that you are using.  Please check out the following article which elaborates more on the matter.
    If you still experience the same issue I would appreciate if you can replicate the issue in a small runnable sample and send it to us in order to investigate it locally.

    Regards,
    Kostadin
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
  7. Rob
    Rob avatar
    43 posts
    Member since:
    Aug 2010

    Posted 18 Nov 2015 in reply to Kostadin Link to this post

    As I said in my first post, the issue happens even if I comment out all the code in the ItemCreated handler.

    I'm not sure what you mean about the custom paging as I do not have it enabled?

  8. Kostadin
    Admin
    Kostadin avatar
    1708 posts

    Posted 23 Nov 2015 Link to this post

    Hi Rob,

    In case you are not using a custom paging then you should not set virtual item count and also current page index. You can check out the following topic which elaborates more on the custom paging. If you still experience the same issue I would appreciate if you can replicate the issue in a small runnable sample which I can debug locally. Additionally I am not sure whether you have remove the code from the ItemDataBound event but you try to access the cells there also so this could be another source of the problem. Generally this type of exception is thrown when you try to access an item from an array but you exceed the length of the collection. I would appreciate if you can point me the exact code which fire the exception by debugging it.

    Regards,
    Kostadin
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
  9. Rob
    Rob avatar
    43 posts
    Member since:
    Aug 2010

    Posted 25 Nov 2015 in reply to Kostadin Link to this post

    I have removed both ServiceWorkTypeGrid.VirtualItemCount and ServiceWorkTypeGrid.CurrentPageIndex, the error still happens.  The error happened before I added either of those things as custom paging was one of the ways I tried to prevent it.

    Kostadin said: I would appreciate if you can point me the exact code which fire the exception by debugging it

    I can't do that because the exception doesn't appear in my code.  The only time it is seen is when the response is delivered to the browser.  No exception is caught by Visual Studio when I am debugging, I have no access to any of the source code shown in the error message.

    Once we have got our release out I will have the time to try and replicate in a sample project, for now I've made the grid edit operations occur in a new window.

  10. Kostadin
    Admin
    Kostadin avatar
    1708 posts

    Posted 30 Nov 2015 Link to this post

    Hello Rob,

    If you managed to replicate the issue in a small runnable sample I will be glad to help you find the cause for this issue.

    Regards,
    Kostadin
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017