I try to order my datagridview but can't. On the web I found and modified this:
List<DataGridViewRow> q = (from item in dataGridView1.Rows.Cast<DataGridViewRow>()
orderby item.Cells[0].Value descending
select item).ToList<DataGridViewRow>();
But it doesn't work because I don't know how to assign this list to the datasource of my datagridview.
Maybe, it is not the correct form to do this. In other projects I put the data on my datagridview in a list and then I execute the linq query on my list and it's works. How is it in datagridview?
Just use the DataGridView.Sort()
method:
dataGridView1.Sort(dataGridView1.Columns[0], ListSortDirection.Descending);
If you decide to use LINQ (maybe more complex ordering, or manipulating the data in some other way), it'd be preferable to act on the original source of data (ie a list), like you said you've done before.
I don't think you can do what you want to do in a generic sort of way, because DataSource
is an object
, so eventually you'll need to cast DataSource
back to whatever the original data type was that you used to populate the DataGridView
with in the first place.
Try this,
List<DataGridViewRow> q = (from item in dataGridView1.Rows.Cast<DataGridViewRow>()
orderby item.Cells[0].Value descending
select item).ToList<DataGridViewRow>();
dataGridView1.DataSource = q.Select(x => x.DataBoundItem).Cast<Employee>().ToList();
For cast I have passed Employee
but you need to pass your class instead of Employee
Or you can bind datasource without cast, like
dataGridView1.DataSource = q.Select(x => x.DataBoundItem).ToList();
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.