Reputation: 77
So I have something like this:
List<Customer> customers;
customers = Customer.databaseproc(parameters);
//databaseproc() is implemented using a data reader and I know it works.
DataGridView dgv;
dgv.DataSource = customers;
That's not the question exactly, but I thought it might be important to provide some context first. If I need to provide more/clearer details, I'd be happy to do so, but at this point, I'm rather new to the SqlConnection stuff as well as windows forms.
The question is this: If I were to try to implement a custom sort (over a field determined by the user at runtime), is there a way for me to (after the above code has already executed and the gridview is visible) programmatically change the order of the rows to reflect those choices in sorting?
Upvotes: 0
Views: 2496
Reputation: 16956
If the requirement is for any random order, I would do this.
Random r = new Random();
customers =customers.OrderBy(x => r.Next(0,r.customers.Count())) // random order.
.ToList();
dgv.DataSource=customers ; // Set new DataSource.
Alternatively, you could also use Guid
to randomize your list.
customers =customers.OrderBy(x => Guid.NewGuid()) // random order.
Check this Usage Demo
Upvotes: 1
Reputation: 29006
Let CustomerName
is a Property in the Customer
class and you want to sort the List based on the CustomerName(or let it be any other property in the class). Then you can sort the List and then assign the DataSource again(As like the comment by @Plutonix). it will be like this:
customers =customers.OrderBy(x => x.CustomerName).ToList(); // Sort the list
dgv.DataSource=customers ; // Re-assign the datasource
Upvotes: 1