title: Gridview sorting in ASP.NET
body: <p>I have a gridview and its data source comes from linq to sql statements:</p>
  
  <pre><code>var query = from user in dataContext.tbl_files
              select new { user.File_Name, user.Upload_Time, user.Uploaded_By };
  
  GridView1.DataSource = query.ToList();
  GridView1.DataBind();
  </code></pre>
  
  <p>I am trying to implement sorting feature of gridview :</p>
  
  <pre><code>public void GridView1_Sorting(object sender, GridViewSortEventArgs e)
  {
      string previousSortExpression = (string)ViewState["SortDirection"];
      string sortExpression = e.SortExpression;
      SortDirection sortDirection = e.SortDirection;
      if (sortExpression.Equals(previousSortExpression))
      {
          sortDirection = SortDirection.Descending;
          ViewState["SortDirection"] = string.Empty;
      }
      else
          ViewState["SortDirection"] = sortExpression;
  
      string direction = sortDirection == SortDirection.Ascending ? "ASC" : "DESC";
      e.SortExpression = string.Format("it.{0} {1}", e.SortExpression, direction);
  
      DataTable dataTable = (DataTable)GridView1.DataSource; // here returns null!
  
      if (dataTable != null)
      {
          DataView dataView = new DataView(dataTable);
          dataView.Sort = e.SortExpression ;
          GridView1.DataSource = dataView;
          GridView1.DataBind();
      }
  }
  </code></pre>
  
  <p>But <code>" DataTable dataTable = (DataTable)GridView1.DataSource; "</code> line returns null however count of datasource is 4. I got this error :</p>
  
  <blockquote>
    <p>{"Unable to cast object of type 'System.Collections.Generic.List<code>1[&lt;&gt;f__AnonymousType0</code>3[System.String,System.Nullable`1[System.DateTime],System.String]]' to type 'System.Data.DataTable'."}</p>
  </blockquote>
  
  <p>How can I sort my gridview and correct my mistake? Thanks..</p>