I am trying to sort the data in gridview
everything is working fine but numeric column(Marks) taking sorting for 1st number only
Code:
protected void gvTrHty_Sorting(object sender, GridViewSortEventArgs e)
{
try
{
this.gviewSorting(e.SortExpression);
}
catch (Exception ex)
{
string arg_15_0 = ex.Message;
}
}
private void gviewSorting(string strSortExp)
{
if (this.ViewState["dvTrain"] == null)
{
DataSet dataSet = this.BindTraining();
dv = dataSet.Tables[0].DefaultView;
}
else
{
DataSet dataSet2 = (DataSet)this.ViewState["dvTrain"];
TrainingHistory.dv = dataSet2.Tables[0].DefaultView;
}
if (TrainingHistory.sortorder)
{
TrainingHistory.sortorder = false;
TrainingHistory.dv.Sort = strSortExp + " DESC";
}
else
{
TrainingHistory.sortorder = true;
TrainingHistory.dv.Sort = strSortExp;
}
this.BindData(TrainingHistory.dv);
}
If I have values in Mark(column) in gridview
Marks----> When I click this for sorting it's taking Marks
1 1
8 1st number only sorted ---> 12
40 21
12 40
21 8
It is treating your "numerical" data as a string and doing the sort against this string value, thus "40" is less than "8".
Your options are:
Implement your own sorting logic, like this:
public sealed class GenericComparer<T> : IComparer<T> { public enum SortOrder { Ascending = 0, Descending = 1 } private string sortColumn; private SortOrder sortingOrder; public string SortColumn { get { return this.sortColumn; } } public SortOrder SortingOrder { get { return this.sortingOrder; } } public GenericComparer(string theSortColumn, SortOrder theSortingOrder) { this.sortColumn = theSortColumn; this.sortingOrder = theSortingOrder; } public int Compare(T x, T y) { PropertyInfo thePropertyInfo = typeof(T).GetProperty(this.sortColumn); IComparable object1 = (IComparable)thePropertyInfo.GetValue(x, null); IComparable object2 = (IComparable)thePropertyInfo.GetValue(y, null); if (this.sortingOrder == SortOrder.Ascending) { return object1.CompareTo(object2); } else { return object2.CompareTo(object1); } } }
Now in your call to .Sort()
method, you pass a new instance of this helper class (passing it the column you want to sort by and the direction you want to sort - ascending or descending).
Since the comparer logic above uses generics, you can pass whatever type you want to sort by (ie int
, DateTime
, or even entire domain objects).
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.