0
List<String> employeeTimings;
    public string[] sTime = {"0000", "0030", "0100", "0130", "0200", "0230", "0300", "0330", "0400", "0430", "0500", "0530", "0600", "0630", "0700", "0730", "0800", "0830", "0900", "0930", "1000", "1030", "1100", "1130", "1200", 
                                 "1230", "1300", "1330", "1400", "1430", "1500", "1530", "1600", "1630", "1700", "1730", "1800", "1830", "1900", "1930", "2000", "2030", "2100", "2130", "2200", "2230", "2300", "2330"};

employeeTimings = new List<String>(sTime);
        int i=0;
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("Location", typeof(string)));
        dt.Columns.Add(new DataColumn("Station", typeof(string)));

        foreach (DataColumn dc in dt.Columns)
        {
            dt.Columns.Add(employeeTimings[i], typeof(string));
            i++;
        }
        SchedulingTableDGV.DataSource = dt;

i get an error "Collection was modified; enumeration operation may not execute." how can i solve this?

Kenneth Teo
  • 3
  • 1
  • 3

5 Answers5

3

You cannot add or remove from the collection you are iterating with a foreach. You need to perform adding or removing actions outside of the foreach.

    foreach (DataColumn dc in dt.Columns)
    {
        dt.Columns.Add(employeeTimings[i], typeof(string)); // Problem.
        i++;
    }

Try this:

foreach (var timing in employeeTimings)
{
    dt.Columns.Add(timing, typeof(string));
}
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
1

You can't modify a collection you are looping over with foreach. The solution in your case is pretty simple: Since you do not use dc inside the loop, why not use a normal for loop, like:

int length = dt.Columns.Length;
for (int i = 0; i < length; i++)
{
    dt.Columns.Add(employeeTimings[i], typeof(string));
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

With LINQ you can do:

    foreach (DataColumn dc in dt.Columns.OfType<DataColumn>().ToArray())
    {
        dt.Columns.Add(employeeTimings[i], typeof(string));
        i++;
    }
TcKs
  • 25,849
  • 11
  • 66
  • 104
0

You are modifying the collection dt.Columns with the Add method while you are iterating over it:

foreach (DataColumn dc in dt.Columns)
{
    dt.Columns.Add(employeeTimings[i], typeof(string));
    i++;
}

Apart from not adding all timing strings this modifies the collection you are adding the columns to.

You should enumerate employeeTimings and add the columns like:

foreach(string s in employeeTimings)
{
    dt.Columns.Add(s, typeof(string));
}
Matten
  • 17,365
  • 2
  • 42
  • 64
0

I guess your true intentions are to add the full employeeTimings list to the datatable columns
If this is right then you should loop on the list not on the columns

foreach (string s in employeeTimings) 
    dt.Columns.Add(s, typeof(string)); 
Steve
  • 213,761
  • 22
  • 232
  • 286