Sorting Data in C# DataTable

I wish to sort my data in DataTable based on a particular column, before assigning that DataTable to a GridView control. Assume below is my table

Table.png

Now, the table needs to be sorted in descending order, based on Total Column. Below are the steps to do the same:


  1. Create a clone of the above table.
  2. Specify the Data Type in clone table, for the sort column as needed. Eg. System.Int32 for integer column.
  3. Import each row from original table to clone table.
  4. Commit the changes in clone table.
  5. Create a DataView on clone table.
  6. Specify the sort column and sort order for the  DataView.
  7. Bind  DataView to  GridView.

     DataTable dtMarks1 = dtMarks.Clone();
            dtMarks1.Columns["Total"].DataType = Type.GetType("System.Int32");

            foreach (DataRow dr in dtMarks.Rows)
            {
                dtMarks1.ImportRow(dr);
            }
            dtMarks1.AcceptChanges();


            DataView dv = dtMarks1.DefaultView;
            dv.Sort = "Total DESC";

            GridView1.DataSource = dv;
            GridView1.DataBind();



Cheers,
Venkatesan Prabu .J
Head, KaaShiv InfoTech

Next Recommended Reading Exporting Data From DataTable To PDF