I am New In C#
I have a problem in My datagrideview i cant make the Column [Size] to be order in the right way (KB >> MB >> GB) or (GB >> MB >> KB) by clicking the Header By the Left Mouse
the value in the Column [Size] is nvarchar(60) and all added as text (0.1 KB or 2 MB ....etc)
how can i do that ?
Handle the SortCompare
even like this:
private void dataGridView1_SortCompare(object sender,
DataGridViewSortCompareEventArgs e)
{
// Sort the size column
if (e.Column.Name == "Size")
{
e.SortResult = new SizeComparer().Compare(
e.CellValue1.ToString(), e.CellValue2.ToString());
e.Handled = true;
}
}
It will use the code below to do the comparison for sorting. This code does a very simple thing: It takes the last two characters (MB, GB) etc. and based on that determines the multiplier. Then it takes that and multiplies it by the number before the unit. For example for 1.0 KB
it will do 1 * 1000
and then compare based on that:
public class ItemSize
{
public string Unit { get; set; }
public double Value { get; set; }
}
public class SizeComparer : IComparer<string>
{
public int Compare(string x, string y)
{
var itemX = new ItemSize { Unit = x.Substring(x.Length - 2), Value = double.Parse(x.Substring(0, x.Length - 2)) };
var itemY = new ItemSize { Unit = y.Substring(y.Length - 2), Value = double.Parse(y.Substring(0, y.Length - 2)) };
SetItemSize(itemX);
SetItemSize(itemY);
return itemX.Value.CompareTo(itemY.Value);
}
private void SetItemSize(ItemSize item)
{
switch (item.Unit)
{
case "KB":
item.Value *= 1000;
break;
case "MB":
item.Value *= 1000000;
break;
case "GB":
item.Value *= 1000000000;
break;
// Add all the other cases
default:
throw new ArgumentException("Looks like you missed one...");
}
}
}
Please make sure to do error handling. Use double.TryParse
if there are cases that parsing can fail.
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.