Home > dotnetjunkies > Sorting DataTable Snippet

Sorting DataTable Snippet

Sorting DataTable Snippet

 private static void SortDataTable(DataTable dt, string sort)
{
DataTable newDT = dt.Clone();
int rowCount = dt.Rows.Count;

DataRow[] foundRows = dt.Select(null, sort); // Sort with Column name
for (int i = 0 ; i < rowCount; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j]=foundRows[i][j];
}
DataRow data_row = newDT.NewRow();
data_row.ItemArray=arr;
newDT.Rows.Add(data_row);
}

//clear the incoming dt
dt.Rows.Clear();

for(int i = 0; i < newDT.Rows.Count; i++)
{
object[] arr = new object[dt.Columns.Count];
for (int j = 0; j < dt.Columns.Count; j++)
{
arr[j]=newDT.Rows[i][j];
}

DataRow data_row = dt.NewRow();
data_row.ItemArray = arr;
dt.Rows.Add(data_row);
}

}

Via http://www.csharpfriends.com/Forums/ShowPost.aspx?PostID=36859

Advertisements
Categories: dotnetjunkies
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: