Search code examples
c#datatablespacedatarow

Add row between other rows


I have a datatable, containning 7 columns. One of the columns is 'Unit-Nr'. Typically the cells in that column would look something like this:

Unit-Nr
A-55
A-55
A-55
A-52
A-52
A-52
A-50

I'm trying to achieve a behavior so I can "seperate" the rows by inserting a new datarow between new 'Unit-Nr'. So it would look like this:

Unit-Nr
A-55
A-55
A-55

A-52
A-52
A-52

A-50

So far I've been trying with the code below but that gives me a System.OutOfMemoryException

for (int i = 0; i < dt.Rows.Count; i++)
{
    if (i > 0 && dt.Rows[i][0].ToString() != dt.Rows[i - 1][0].ToString())
    {
        DataRow row = dt.NewRow();
        object[] oArray = new object[] { "", "", "", "", "", "", "" };

        row.ItemArray = oArray;

        dt.Rows.InsertAt(row, i - 1);
    }
}

Solution

  • You should insert the rows at the position you are at that moment, not with -1.

    You get an out of range exception becaus your code is adding an infinite amount of empty rows, you can stop this by increasing the I after you inserted a empty row.

    Another tip, i > 0 can be skipped if you start the for loop with 1 instead of 0

    for (int i = 1; i < dt.Rows.Count; i++)
    {
        if (dt.Rows[i][0].ToString() != dt.Rows[i - 1][0].ToString())
        {
            DataRow row = dt.NewRow();
            object[] oArray = new object[] { ""};
    
            row.ItemArray = oArray;
    
            dt.Rows.InsertAt(row, i);
            i++;
        }
    }