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;
       dgMembers.DataBind();
   }

   private DataTable GetDataTable() {
       //create table
       DataTable dt = new DataTable("Members");
       dt.Columns.Add("ID",Type.GetType("System.Int32"));
       dt.Columns.Add("LastName",Type.GetType("System.String"));
       dt.Columns.Add("Lectures",Type.GetType("System.Int32"));

       //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;
               dt.Rows.Add(dr);
           } else {
               dr = dt.NewRow();
               dr["LastName"] =  "Anders";
               dr["Lectures"] = 3;
               dt.Rows.Add(dr);

           }
       }

       return dt;
   }




</script>
<html>
<head>
</head>
<body>
<form runat="server">
<asp:DataGrid id="dgMembers" runat="server"></asp:DataGrid>
</form>
</body>
</html>

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post