I have a listview with 4 columns – Name, Extension, Size and Location. I have a method that takes the file size in bytes and converts to KB, MB, GB, etc as needed. An example output would be a 1024 byte file which is printed as ‘1KB’. This value is then placed in the listview.
What I need to do is sort the size column intelligently. Right now the sorting is just a simple comparison so 1025 KB is higher than 1024 MB. How can I make it ‘size aware’?
My current sorting code is from this KB article: http://support.microsoft.com/kb/319401 And here is my code that generates the file size text:
public static string getDynamicFileSize(string fileName) { FileInfo fi = new FileInfo(fileName); long sizeInBytes = fi.Length; if (sizeInBytes >= 1073741824) { double sizeInGB = sizeInBytes / Math.Pow(1024, 3); return Math.Round(sizeInGB, 2) + ' GB'; } if (sizeInBytes >= 1048576) { double sizeInMB = sizeInBytes / Math.Pow(1024, 2); return Math.Round(sizeInMB, 2) + ' MB'; } if (sizeInBytes >= 1024) { double sizeInKB = sizeInBytes / Math.Pow(1024,1); return Math.Round(sizeInKB, 2) + ' KB'; } //No conversion needed return sizeInBytes + ' bytes'; }
Thank you.
Most every object in .NET has a Tag member. This is a place where you can stuff anything extra you need to. In your case, I would stuff the file size in bytes into the ListViewSubItem.Tag property. Then, your sort algorithm can use that to sort by instead of the column text.