score:2

Accepted answer

You can't use the DataSource property of the grid to fetch the data source. It is only available after it is set and to the end of that postback. You'll need the fetch the data from the database again.
Something like this:

public void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
  var users = (from user in dataContext.tbl_files
              select new { user.File_Name, user.Upload_Time, user.Uploaded_By }).ToList().AsEnumerable();

  switch(e.SortExpression)
  {
     case "File_Name":
       users = users.OrderBy(x => x.File_Name);
       break;
     case "Upload_Time":
       users = users.OrderBy(x => x.Upload_Time);
       break;
     case "Uploaded_By":
       users = users.OrderBy(x => x.Uploaded_By);
       break;
  }
  if(e.SortDirection == SortDirection.Descending)
    users = users.Reverse();

  GridView1.DataSource = users;
  GridView1.DataBind();
}

score:1

Above answer is correct first you need to assign datasource to gridview again as sorting event is called.

So have to store the data somewhere.

For retrieving the datasource from grid you can follow below steps

The problem lies as you are assigning linq result as datasource of gridview and then taking datatable from the gridview datasource.

Try this code

BindingSource bs = (BindingSource )Gv.DataSource;
DataTable Dt = (DataTable ) bs.DataSource;

Contact if you have any doubt


Related Articles