Asp.net: Sorting with gridview and objectDataSource [closed]

一世执手 提交于 2019-12-26 13:33:39

问题


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


回答1:


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:


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;
        }


来源:https://stackoverflow.com/questions/4876660/asp-net-sorting-with-gridview-and-objectdatasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!