简体   繁体   中英

Programmatically reorder rows in a datagridview

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?

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM