Friday, October 16, 2009

Sort a DataTable

Here is a very easy way to sort the records in a DataTable by one of the columns.

    public static DataTable SortDataTable(DataTable dt, string sortColumn, string direction)
{
DataTable tempDataTable = dt.Clone();
int rowCount = dt.Rows.Count;
int columnCount = dt.Columns.Count;
DataRow[] allRows = dt.Select(null, sortColumn + " " + direction.ToUpper());

for (int i = 0; i < rowCount; i++)
{
object[] rowArray = new object[columnCount];
for (int j = 0; j < columnCount; j++)
{
rowArray[j] = allRows[i][j];
}
DataRow tempRow = tempDataTable.NewRow();
tempRow.ItemArray = rowArray;
tempDataTable.Rows.Add(tempRow);
}

dt.Rows.Clear();
for (int i = 0; i < tempDataTable.Rows.Count; i++)
{
object[] rowArray = new object[columnCount];
for (int j = 0; j < columnCount; j++)
{
rowArray[j] = tempDataTable.Rows[i][j];
}
DataRow tempRow = dt.NewRow();
tempRow.ItemArray = rowArray;
dt.Rows.Add(tempRow);
}

return (dt);
}

No comments:

Post a Comment