简体   繁体   中英

DataGridView Column Sorting Descending order C#

I got one little problem about sorting data in DataGridView control. Before that, I made BinaryWriter form that saves my data. I'm using this line of code to sort my column in Descending order in BinaryReader form.

this.dataGridView1.Sort(this.dataGridView1.Columns[4], ListSortDirection.Descending);

I have to sort these numbers in descending order - 12, 10, 7 and 5. This is the 4th column of my DataGrid . All fine, but everytime my last saved row of data is not sorted and only stay here.

How can I sort the last row ? Something is missing or is there other solution ? Thanks!

This question is already answered at MSDN

This is by design, the "last row" is not belong to the data collection of the DataGridView, it's just an empty row for inputing, I don't think it make sense to sort it with the real data records.

So for sorting, you can get DataTable , perform sorting on it and then bind sorted DataTable to DataGridView

Sample code

var src = //get DataTable from your source
var dv = src.DefaultView;
dv.Sort = "<your column name> desc";
src = dv.ToTable();

dataGridView.DataSource = src;

Ok, so if you're adding new data into the last row then it won't be included in the sort as it's not committed data. It's still classed as 'dirty' at this point. You need to commit the data when it's saved and then order after that's been done.

EDIT

To achieve what you want you should validate the data in the new data row first and then use the datagrid.currentrow.datagrid.endedit() as found here . This can be done with something like this (taken from linked question incase the question gets removed in the future):

void dataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
    // Ignore Row if it's not dirty
    if (!dataGridView.IsCurrentRowDirty)  
        return;

    // Validate all cells in the current row.
}

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