How to sort a DataTable before passing it on to DataGrid in ASP.NET

If you are displaying a DataTable with a DataGrid and would like to have it sorted by a column, here is the two-line solution (copy it to a DataView, sort the DataView, and then define the DataSource of the DataGrid as the DATAVIEW, not the DataGrid.

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<script runat="server">

   public void Page_Load(Object sender, EventArgs E) {

       DataTable dt = GetDataTable();

       //sort the DataTable
       DataView dv=dt.DefaultView;
       dv.Sort="LastName DESC";

       dgMembers.DataSource = dv;

   private DataTable GetDataTable() {
       //create table
       DataTable dt = new DataTable("Members");

       //create fields
       DataColumn[] pk = new DataColumn[1];
       pk[0] = dt.Columns["ID"];
       dt.PrimaryKey = pk;
       dt.Columns["ID"].AutoIncrement = true;
       dt.Columns["ID"].AutoIncrementSeed = 1;
       dt.Columns["ID"].ReadOnly = true;

       //fill rows
       DataRow dr;
       for(int x=1;x<=10;x++) {
           //make every other one different
           if(Math.IEEERemainder(x,2) == 0) {
               dr = dt.NewRow();
               dr["LastName"] =  "Riss";
               dr["Lectures"] = 14;
           } else {
               dr = dt.NewRow();
               dr["LastName"] =  "Anders";
               dr["Lectures"] = 3;


       return dt;

<form runat="server">
<asp:DataGrid id="dgMembers" runat="server"></asp:DataGrid>
Next Post Previous Post
No Comment
Add Comment
comment url