Tuesday, January 29, 2008

How to Sort the datatable

private static void SortDataTable(DataTable dataTable, string sortColumn)
{
DataTable tempDataTable = dataTable.Clone();
int rowCount = dataTable.Rows.Count;
int columnCount = dataTable.Columns.Count;
DataRow[] allRows = dataTable.Select(null, sortColumn); // Sorting with column name.

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);
}

dataTable.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 = dataTable.NewRow();
tempRow.ItemArray = rowArray;
dataTable.Rows.Add(tempRow);
}
}

No comments:

 
Feedback Form