We all know that we can sort the rows in DataTable by making a simple use of DefaultView. But now if i want a few conditional rows to be shuffled in the table; i dont have anything inbuilt in .net.
Now if I want to select a few conditional rows in the table and move them to the top of the table.
Let us do it by going through a simple example as shown below:
//We create a test dataTable and its columns
DataTable dtTestData = new DataTable();
dtTestData.Columns.Add("id");
dtTestData.Columns.Add("FirstName");
dtTestData.Columns.Add("LastName");
//We add rows to the created Test DataTable
DataRow drw = dtTestData.NewRow();
drw["id"] = 1;
drw["FirstName"] = "Steve";
drw["LastName"] = "Waugh";
dtTestData.Rows.Add(drw);
drw = dtTestData.NewRow();
drw["id"] = 2;
drw["FirstName"] = "Mark";
drw["LastName"] = "Waugh";
dtTestData.Rows.Add(drw);
dtTestData.AcceptChanges();
drw = dtTestData.NewRow();
drw["id"] = 3;
drw["FirstName"] = "Jhon";
drw["LastName"] = "Smith";
dtTestData.Rows.Add(drw);
dtTestData.AcceptChanges();
drw = dtTestData.NewRow();
drw["id"] = 2;
drw["FirstName"] = "Shane";
drw["LastName"] = "Warne";
dtTestData.Rows.Add(drw);
dtTestData.AcceptChanges();
//Select a group of rows at specified condition (here we have condition id=3)
DataRow[] selectedRow = dtTestData.Select("id=3");
if (selectedRow.Length > 0)
{
DataRow drNewRow = dtTestData.NewRow();
//Iterate through the Resultant DataRows
foreach (DataRow rowSelected in selectedRow)
{
//Assign the resultant row's ItemArray to NewRow's Item Array.
drNewRow = dtTestData.NewRow();
drNewRow.ItemArray = rowSelected.ItemArray;
//Removing the resultant row from the Table and adding the new row to the Table.
dtTestData.Rows.Remove(rowSelected);
dtTestData.Rows.InsertAt(drNewRow, 0);
}
}
Now when you view this dtTestData; this DataTable will contain the selected resultant rows on the top.
Here we simply select a specific rows at a specified condition. Then we take a new DataRow for that particular table. Assign the resultant datarow's itemarray to the newdatarow's item array. Then after we delete the resultant data row from the table and add the New data row at the start index of the table ( i.e. 0th index).
Iterating in this way, moves all the resultant rows at top of the Table.
Similarly we can move any of the conditional resultant row to any row index of the DataTable.