Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

c# - asp.net ListView sorting numerically

I have a list view which is bound to a DataTable source. The sorting works, kinda.

For text is fine but not so much for numbers.

For example if I sort 1-12 descending I get 9,8,7,6,5,4,3,2,12,11,10,1.

How to get the proper sequence?

I am using:

lvPos.Sort("Position", SortDirection.Descending);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're likely going to have to do the sorting yourself instead of relying on ListView's sort method.

If you're sorting just using code, this is very easy. Just shove your DataTable into a DataView and use the DataView's Sort method. Then bind to your DataView instead of your DataTable.

var view = new DataView(dtTable);
view.Sort = "Position"; //or "Position DESC"
lvPos.DataSource = view;
lvPos.DataBind();  //use lvPos.DataBind(true) to raise the "OnDataBinding" event.

If you're sorting from the ListView's sort methods (i.e. you have something in the page triggering the ListView.Sorting/Sorted events), then you would have to hook on to the Sorting event and cancel it. Follow up with the previous technique of shoving the DataTable into a DataView (or re-use the DataView!), sort by the new expression, and rebind your data.

private void lvPos_Sorting(object sender, ListViewSortEventArgs args)
{
   var view = new DataView(dtTable);
   view.Sort = args.SortExpression;
   lvPos.DataSource = view;
   lvPos.DataBind();
   args.Cancel = true;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...