Asp.net: Sorting with gridview and objectDataSource

1.2k views Asked by At

how I do a sorting in a gridView with data bound by a ObjectDataSource?

2

There are 2 answers

8
khr055 On BEST ANSWER

Here is a question that has been previously answered.

For the actual sorting, you would call

collectionOfObjects.OrderBy(x => x.PropertyToSortOn);

You could use a switch to change what to sort on based on what is passed into the method via the args. So it would look a little more like this

switch(propertyName)
{
  case "property1":
    collectionOfObjects.OrderBy(x => x.PropertyToSortOn);
    break;
  case "property2":
    collectionOfObjects.OrderBy(x => x.OtherPropertyToSortOn);
    break;

  ...

}

Hope this helps! :)

2
Gerardo Jaramillo On

If is more easy for you, why dont you try to sort it from the store procedure or the query. Maybe is not the optimun solution but it could be easier.

EDIT

IF you want to do it programattically with the gridview controls, Take a look at this code:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataBind();
        }


        protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            DataTable dtSortTable = GridView1.DataSource as DataTable;
            if (dtSortTable != null)
            {
                DataView dvSortedView = new DataView(dtSortTable);
                dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
                GridView1.DataSource = dvSortedView;
                GridView1.DataBind();
            }
        }

        private string getSortDirectionString(SortDirection sortDireciton)
        {
             string newSortDirection = String.Empty;
             if (sortDireciton == SortDirection.Ascending)
            {
                newSortDirection = "ASC";
            }
            else
            {
                newSortDirection = "DESC";
            }
            return newSortDirection;
        }