I have a DataGridView in a Winforms application. I want to select a set of rows in it and sort those rows by a column (Timestamp)...
The rest of the rows should remain as they originally were.. Can this be done using the sort property of DGV
Thanks
Can this be done using the sort property of DGV
No
The Sort
method on the DataGridView
is used for a bit more simple sorting. Such as Ascending or Descending sorting and the SortOrder
property is also just for "simple" sorting.
Can this behavior be implemented? Sure.
I think the easiest way to do this, is this:
DataGridView
However you need to think about how you want to handle if you selecte items that are not followed by each other, for instance if you select index { 1, 3, 6, 9 }
you might stil lwant to append this to index 1
.
Edit
Okay so I played around with this a little bit and came up with a way that you can implement this. It's not very optimized but you'll get the idea on how I meant.
First of all this is my SortSelectedIndices
-method that I use:
static IEnumerable<T> SortSelectedIndices<T>(
IEnumerable<T> values,
IEnumerable<int> selectedIndices,
Func<IEnumerable<T>, IEnumerable<T>> sort)
{
var selectedValues = new List<T>();
for (var i = 0; i < selectedIndices.Count(); i++)
selectedValues.Add(values.ElementAt(selectedIndices.ElementAt(i)));
var sortedList = sort(selectedValues);
var finalList = new List<T>();
var startPositionFound = false;
for(var i = 0; i < values.Count(); i++)
{
if (selectedIndices.Contains(i))
{
if (startPositionFound) continue;
startPositionFound = true;
finalList.AddRange(sortedList);
}
else
finalList.Add(values.ElementAt(i));
}
return finalList;
}
Then I call it like this:
static void Main(string[] args)
{
var unsorted = new[] {3, 5, 6, 1, 2, 87, 432, 23, 46, 98, 44};
var selected = new[] {1, 4, 7};
Print(unsorted);
var sort = new Func<IEnumerable<int>, IEnumerable<int>>(
(x) => x.OrderBy(y => y).ToList());
var sorted = SortSelectedIndices(unsorted, selected, sort);
Print(sorted);
}
And this prints out the following:
{ 3,5,6,1,2,87,432,23,46,98,44 }
{ 3,2,5,23,6,1,87,432,46,98,44 }
I am just using a simple method here to print this out to the console:
static void Print<T>(IEnumerable<T> values)
{
Console.Write("{ ");
Console.Write(string.Join(",", values));
Console.WriteLine(" }");
}
So what you can do is to have a "sort"-button, when it's pressed you invoke SortSelectedIndices
and then rebind the list when you're done. Remember I have not profiled or refactored this code, it might not be as fast as you like, I just want to give you an idea on what you can do to acheive the solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With