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

Collection was modified; enumeration operation may not execute.

1 Answer 136 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Dale Palmer
Top achievements
Rank 1
Dale Palmer asked on 06 Nov 2014, 04:19 PM
Hi,

I was hoping someone could help.  I have a radgrid that is populated by a list in code behind and have a checkbox in a Gridtemplate column. There is a button outside the grid that should collect all items that have checkbox checked and add results to a new db table.

This seem to work fine when grid is loaded and not filtered, however when the grid is filtered I get he following error:

Server Error in '/' Application.Collection was modified; enumeration operation may not execute.Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.

Source Error: 

Line 444: dbContext.SaveChanges();
Line 445:
Line 446: foreach (GridDataItem item in rgTracker.MasterTableView.Items)
Line 447: {
Line 448: CheckBox chkInvoiced = (CheckBox)item.FindControl("chkInvoiced");
Source File: e:\DropBox\Optimum Job tracker\Optimum\Pages\PensionLiteReport.aspx.cs    Line: 446 

Stack Trace: 

[InvalidOperationException: Collection was modified; enumeration operation may not execute.]
System.Collections.ArrayListEnumeratorSimple.MoveNext() +11165697
Optimum.Pages.PensionLiteReport.btnAddInvoice_Click(Object sender, EventArgs e) in e:\DropBox\Optimum Job tracker\Optimum\Pages\PensionLiteReport.aspx.cs:446
System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e) +116
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +101
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +9664630
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212

Here is the button and radgrid:

<asp:LinkButton ID="btnAddInvoice" runat="server" CssClass="button small radius" Text="Add Checked to New Invoice" OnClick="btnAddInvoice_Click"></asp:LinkButton>
            <asp:Literal runat="server" ID="litAddInvoice"></asp:Literal>
            <div class="reset">
                 
                <telerik:RadGrid ID="rgTracker" runat="server"
                    AllowSorting="true" AllowPaging="true" PageSize="100" OnItemCreated="rgTracker_ItemCreated"
                    OnNeedDataSource="rgTracker_NeedDataSource"
                    AllowFilteringByColumn="True"
                    OnItemCommand="rgTracker_ItemCommand"
                    OnItemDataBound="rgTracker_ItemDataBound"
                    Skin="Windows7"
                     
                    OnPreRender="rgTracker_PreRender">
                    <ExportSettings HideStructureColumns="true">
                    </ExportSettings>
                    <GroupingSettings CaseSensitive="false" />
                    <MasterTableView AutoGenerateColumns="false" EnableHierarchyExpandAll="true" DataKeyNames="rdID, jobID" >
                         
                        <PagerStyle PageSizes="10,50,100,200,500" Mode="NextPrevAndNumeric" PageSizeLabelText="Show results: " Position="TopAndBottom" AlwaysVisible="true" />
                         
                        <Columns>
                            <telerik:GridBoundColumn DataField="rdID" Visible="false" ReadOnly="true" UniqueName="rdID" ForceExtractValue="Always" ConvertEmptyStringToNull="true"></telerik:GridBoundColumn>
                            <telerik:GridBoundColumn DataField="jobID" Visible="false" ReadOnly="true" UniqueName="jobID" ForceExtractValue="Always" ConvertEmptyStringToNull="true"></telerik:GridBoundColumn>
                            <telerik:GridHyperLinkColumn HeaderText="Customer Name" DataTextField="customerName" UniqueName="customerName" DataNavigateUrlFields="jobID" DataNavigateUrlFormatString="/pensionlitedetail/{0}" >
                                <HeaderStyle Width="150px" />
                            </telerik:GridHyperLinkColumn>
                            <telerik:GridBoundColumn HeaderText="Postcode" DataField="customerPostcode" UniqueName="customerPostcode" FilterControlWidth="30px" ReadOnly="true">
                                <HeaderStyle Width="50px" />
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn HeaderText="Phone" DataField="customerPhone" UniqueName="customerPhone" FilterControlWidth="70px" ReadOnly="true">
                                <HeaderStyle Width="90px" />
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn HeaderText="Pension Value" DataField="customerPensionValue" UniqueName="customerPensionValue" DataFormatString="{0:C}" FilterControlWidth="40px" ReadOnly="true">
                                <HeaderStyle Width="75px" />
                            </telerik:GridBoundColumn>
                            <telerik:GridDateTimeColumn HeaderText="Sale Date" DataField="saleDate" UniqueName="saleDate" DataFormatString="{0:g}" PickerType="DatePicker" EnableRangeFiltering="true" FilterControlWidth="100px" EnableTimeIndependentFiltering="true" ReadOnly="true">
                                <HeaderStyle Width="120px" />
                            </telerik:GridDateTimeColumn>
                            <telerik:GridDateTimeColumn HeaderText="Appt Date" DataField="apptDate" UniqueName="apptDate" DataFormatString="{0:g}" PickerType="DatePicker" EnableRangeFiltering="true" FilterControlWidth="100px" EnableTimeIndependentFiltering="true" ReadOnly="true">
                                <HeaderStyle Width="120px" /></telerik:GridDateTimeColumn>
                            <telerik:GridDateTimeColumn HeaderText="Updated" DataField="updatedDate" UniqueName="updatedDate" DataFormatString="{0:g}" PickerType="DatePicker" EnableRangeFiltering="true" FilterControlWidth="100px" EnableTimeIndependentFiltering="true" ReadOnly="true">
                                <HeaderStyle Width="120px" /></telerik:GridDateTimeColumn>
                            <telerik:GridBoundColumn HeaderText="Current Status" DataField="currentStatus" UniqueName="currentStatus" ReadOnly="true">
                                <HeaderStyle Width="100px" />
                                <FilterTemplate>
                                    <telerik:RadComboBox ID="RadComboBoxStatus" AppendDataBoundItems="true" SelectedValue='<%# ((GridItem)Container).OwnerTableView.GetColumn("currentStatus").CurrentFilterValue %>'
                                        runat="server" OnClientSelectedIndexChanged="StatusIndexChanged" Skin="Windows7" Width="200px">
                                        <Items>
                                            <telerik:RadComboBoxItem Text="All" />
                                            <telerik:RadComboBoxItem Text="Lead Pending" Value="Lead Pending" />
                                            <telerik:RadComboBoxItem Text="Lead Accepted" Value="Lead Accepted" />
                                            <telerik:RadComboBoxItem Text="Lead Rejected" Value="Lead Rejected" />
                                        </Items>
                                    </telerik:RadComboBox>
                                    <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
                                        <script type="text/javascript">
                                            function StatusIndexChanged(sender, args) {
                                                var tableView = $find("<%# ((GridItem)Container).OwnerTableView.ClientID %>");
                                                tableView.filter("currentStatus", args.get_item().get_value(), "EqualTo");
                                            }
                                         
                                        </script>
                                    </telerik:RadScriptBlock>
                                </FilterTemplate>
                            </telerik:GridBoundColumn>
                            <telerik:GridBoundColumn HeaderText="Invoiced" DataField="invoiced" UniqueName="invoiced" Display="false" ForceExtractValue="Always" ReadOnly="true">
                                <HeaderStyle Width="50px" />
                            </telerik:GridBoundColumn>
                            <telerik:GridTemplateColumn UniqueName="InvoicedCheckboxColumn" AllowFiltering="false">
                                <HeaderStyle Width="20px" />
                                 
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkInvoiced" runat="server" />
                                </ItemTemplate>
                                <HeaderTemplate>
                                    Invoiced<br /><asp:CheckBox ID="chkInoicedHeader" runat="server" OnCheckedChanged="chkInoicedHeader_CheckedChanged" AutoPostBack="true" />
                                </HeaderTemplate>
                            </telerik:GridTemplateColumn>
                            <telerik:GridBoundColumn HeaderText="Credit" DataField="credited" UniqueName="credited" Display="false" ForceExtractValue="Always" ReadOnly="true">
                                <HeaderStyle Width="50px" />
                            </telerik:GridBoundColumn>
                            <telerik:GridTemplateColumn UniqueName="CreditedCheckboxColumn" AllowFiltering="false">
                                <HeaderStyle Width="20px" />
                                 
                                <ItemTemplate>
                                    <asp:CheckBox ID="chkCredited" runat="server" />
                                </ItemTemplate>
                                <HeaderTemplate>
                                    Credited<br /><asp:CheckBox ID="chkCreditedHeader" runat="server" OnCheckedChanged="chkCreditedHeader_CheckedChanged" AutoPostBack="true" />
                                </HeaderTemplate>
                            </telerik:GridTemplateColumn>
                        </Columns>
                         
                    </MasterTableView>
                </telerik:RadGrid>
            </div>

and here is the related codebehind:

protected void rgTracker_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
             
 
            rgTracker.DataSource = GetData();
        }
 
        protected void rgTracker_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
 
        }
 
        protected void rgTracker_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem dataItem = (GridDataItem)e.Item;
                string cStatus = dataItem["currentStatus"].Text;
 
                if (cStatus == "Lead Rejected")
                {
                    dataItem.BackColor = Color.LightCoral;
                }
                if (cStatus == "Lead Accepted")
                {
                    dataItem.BackColor = Color.LightGreen;
                }
 
                CheckBox chkInvoiced = (CheckBox)e.Item.FindControl("chkInvoiced");
                string sInv = dataItem["invoiced"].Text;
                bool bInv = false;
                Boolean.TryParse(sInv, out bInv);
                if (bInv)
                {
                    chkInvoiced.Checked = true;
                    chkInvoiced.Enabled = false;
                }
 
                CheckBox chkCredited = (CheckBox)e.Item.FindControl("chkCredited");
                string sCred = dataItem["credited"].Text;
                bool bCred = false;
                Boolean.TryParse(sCred, out bCred);
                if (bCred)
                {
                    chkCredited.Checked = true;
                    chkCredited.Enabled = false;
                }
 
            }
        }
 
        protected void rgTracker_PreRender(object sender, EventArgs e)
        {
 
        }
 
        protected void rgTracker_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            GridFilteringItem filteringItem = e.Item as GridFilteringItem;
            if (filteringItem != null)
            {
                LiteralControl literalTo1 = filteringItem["saleDate"].Controls[3] as LiteralControl;
                literalTo1.Text = "<br />To:";
 
                LiteralControl literalTo2 = filteringItem["apptDate"].Controls[3] as LiteralControl;
                literalTo2.Text = "<br />To:";
 
                LiteralControl literalTo3 = filteringItem["updatedDate"].Controls[3] as LiteralControl;
                literalTo3.Text = "<br />To:";
            }
        }
 
        protected void chkInoicedHeader_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox headerCheckBox = (sender as CheckBox);
            foreach (GridDataItem dataItem in rgTracker.MasterTableView.Items)
            {
                if ((dataItem.FindControl("chkInvoiced") as CheckBox).Enabled)
                {
                    (dataItem.FindControl("chkInvoiced") as CheckBox).Checked = headerCheckBox.Checked;
                    dataItem.Selected = headerCheckBox.Checked;
                }
            }
        }
 
        protected void chkCreditedHeader_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox headerCheckBox = (sender as CheckBox);
            foreach (GridDataItem dataItem in rgTracker.MasterTableView.Items)
            {
                if ((dataItem.FindControl("chkCredited") as CheckBox).Enabled)
                {
                    (dataItem.FindControl("chkCredited") as CheckBox).Checked = headerCheckBox.Checked;
 
                    dataItem.Selected = headerCheckBox.Checked;
                }
            }
        }
 
        protected void btnAddInvoice_Click(object sender, EventArgs e)
        {
            //TODO: Wire in credits and check for duplicate sales
            Invoice inv = new Invoice();
 
            inv.ClientID = 11;
            inv.InvoiceDate = DateTime.Now;
 
            dbContext.Invoices.Add(inv);
            dbContext.SaveChanges();
             
            foreach (GridDataItem item in rgTracker.MasterTableView.Items)
            {
                CheckBox chkInvoiced = (CheckBox)item.FindControl("chkInvoiced");
                if (chkInvoiced.Checked && chkInvoiced.Enabled)
                {
                    //ReportDetails rd = (ReportDetails)item.DataItem;
 
                    //litAddInvoice.Text += string.Format("<div data-alert class='alert-box info radius'>{0} {1} - {2}</div>", rd.customerName, rd.customerPhone, rd.jobId);
 
                    string strJID = item.GetDataKeyValue("jobID").ToString();
                    litAddInvoice.Text += string.Format("<div data-alert class='alert-box info radius'>Job ID: {0}</div>", strJID);
 
                    int intJID = 0;
                    Int32.TryParse(strJID, out intJID);
 
                    Job j = new Job();
                    j = dbContext.Jobs.Where(x => x.ID == intJID).FirstOrDefault();
 
                    if (j.ID > 0)
                    {
                        InvoiceDetail id = new InvoiceDetail();
                        id.JobID = j.ID;
                        id.Credit = false;
                        id.JobSchemaID = j.JobSchemata.OrderByDescending(x => x.ID).Select(x => x.ID).FirstOrDefault();
                        id.StatusWhenInvoiced = j.JobSchemata.OrderByDescending(x => x.ID).Select(x => x.JobStage1.JobStage1).FirstOrDefault();
                        id.InvoiceID = inv.ID;
 
                        dbContext.InvoiceDetails.Add(id);
                        dbContext.SaveChanges();
                    }
                }
                CheckBox chkCredited = (CheckBox)item.FindControl("chkCredited");
                if (chkCredited.Checked && chkCredited.Enabled)
                {
                    //ReportDetails rd = (ReportDetails)item.DataItem;
 
                    //litAddInvoice.Text += string.Format("<div data-alert class='alert-box info radius'>{0} {1} - {2}</div>", rd.customerName, rd.customerPhone, rd.jobId);
 
                    string strJID = item.GetDataKeyValue("jobID").ToString();
                    litAddInvoice.Text += string.Format("<div data-alert class='alert-box warning radius'>Job ID: {0}</div>", strJID);
 
                    int intJID = 0;
                    Int32.TryParse(strJID, out intJID);
 
                    Job j = new Job();
                    j = dbContext.Jobs.Where(x => x.ID == intJID).FirstOrDefault();
 
                    if (j.ID > 0)
                    {
                        InvoiceDetail id = new InvoiceDetail();
                        id.JobID = j.ID;
                        id.Credit = true;
                        id.JobSchemaID = j.JobSchemata.OrderByDescending(x => x.ID).Select(x => x.ID).FirstOrDefault();
                        id.StatusWhenInvoiced = j.JobSchemata.OrderByDescending(x => x.ID).Select(x => x.JobStage1.JobStage1).FirstOrDefault();
                        id.InvoiceID = inv.ID;
 
                        dbContext.InvoiceDetails.Add(id);
                        dbContext.SaveChanges();
                    }
                }
 
                rgTracker.Rebind();
            }
 
            litAddInvoice.Text += "<div data-alert class='alert-box success radius'>Invoice Generated</div>";
        }

Any help would be greatly appreciated

Cheers

Dale

1 Answer, 1 is accepted

Sort by
0
Kostadin
Telerik team
answered on 11 Nov 2014, 09:39 AM
Hi Dale,

I already answered the support ticket that you have opened so I would recommend you to continue our conversation there and close this forum thread.

Regards,
Kostadin
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.

 
Tags
Grid
Asked by
Dale Palmer
Top achievements
Rank 1
Answers by
Kostadin
Telerik team
Share this question
or