简体   繁体   中英

Customize order by in Gridview rows

I want to order my gridview like the following

Product Name

FL - STATEWIDE (Primary)

FL - LEE COUNTY

FL - OKALOOSA COUNTY

MS - STATEWIDE (Primary)

MS - KENT COUNTY

I can not order by product. Because if the word primary is contained in the product name, then it should come first.

How can I achieve this?

Once you have read in your datatable, you can then use LINQ to order it

        dtbl = (
                 from item in dtbl.AsEnumerable()
                 select item
               ).OrderBy(x => x.Field<string>("Product Name").Contains("Primary") ? 0 : 1).
                 ThenBy(x => x.Field<string>("Product Name")).CopyToDataTable();

Output

FL - STATEWIDE (Primary)

MS - STATEWIDE (Primary)

FL - LEE COUNTY

FL - OKALOOSA COUNTY

MS - KENT COUNTY

If you need to order by State first (with Primary at the top)

        dtbl = (
                 from item in dtbl.AsEnumerable()
                 select item
               ).OrderBy(x => x.Field<string>("Product Name").Substring(0,2))
                 ThenBy(x => x.Field<string>("Product Name").Contains("Primary") ? 0 : 1).
                 ThenBy(x => x.Field<string>("Product Name")).CopyToDataTable();

Output

FL - STATEWIDE (Primary)

FL - LEE COUNTY

FL - OKALOOSA COUNTY

MS - STATEWIDE (Primary)

MS - KENT COUNTY

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM