havin havin - 23 days ago 8
Vb.net Question

Datatable second row to first row

In My Datatable iam getting 2 rows like

Name Age City

A 20 c

B 20 c


Now i need like second row shifted to First Row and vice versa

Name Age City

B 20 c

A 20 c


How can i do it.

Answer

If you want to swap two rows you can use following approach:

for (int i = 0; i < table.Rows.Count; i += 2)
{
    object[] row1Items = table.Rows[i].ItemArray;        // works because ItemArray creates a new object[]
    table.Rows[i].ItemArray = table.Rows[i+1].ItemArray; // move second to first
    table.Rows[i+1].ItemArray = row1Items;               // move first to second
}

It even works with more than two, it swaps every consecutive pair of rows.