How do you Sort a DataTable given column and direction?

Sam Gentile picture Sam Gentile · Feb 15, 2011 · Viewed 200.8k times · Source

I need to resort, in memory, a DataTable based on a column and direction that are coming from a GridView. The function needs to look like this:

public static DataTable resort(DataTable dt, string colName, string direction)
{
    DataTable dtOut = null;

    ....
}

I need help filling in this function. I think I can use a Select statement but I am not sure how. I can't click on Comments because of this browser but you can show me an in-place or new DataTable solution, either one. For the people showing me pointers, please, I need a coded function similar to the one prototyped.

How about:

// ds.Tables[0].DefaultView.Sort="au_fname DESC";
   public static void Resort(ref DataTable dt, string colName, string direction)
   {
        string sortExpression = string.Format("{0} {1}", colName, direction);
        dt.DefaultView.Sort = sortExpression;
   }

Answer

Berkay Turancı picture Berkay Turancı · Dec 25, 2012

I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"

public static DataTable resort(DataTable dt, string colName, string direction)
{
    DataTable dtOut = null;
    dt.DefaultView.Sort = colName + " " + direction;
    dtOut = dt.DefaultView.ToTable();
    return dtOut;
}

OR without creating dtOut

public static DataTable resort(DataTable dt, string colName, string direction)
{
    dt.DefaultView.Sort = colName + " " + direction;
    dt = dt.DefaultView.ToTable();
    return dt;
}