开发者

Reapplying Sort To DataGrid?

开发者 https://www.devze.com 2023-03-31 04:58 出处:网络
I have a DataGridView. I can click the column headers to sort the data by whichever column header I click.

I have a DataGridView.

I can click the column headers to sort the data by whichever column header I click.

I have some functionality that clears the DataGridView, and repopulates it with data. The problem I'm having is that the indication of a sort in a particular column (the gray upside up or upside down triangle) still remains even though the data isn't sorted by that column because it was just loaded into the D开发者_StackOverflow社区ataGridView.

Is there any way I can reapply the sort right after the new data is added?

Edit: If this isn't very easy, just being able to get rid of that gray upside-up or upside-down triangle is good enough so it is clear that the data is not sorted.


This should do the remove

Column.HeaderCell.SortGlyphDirection = SortOrder.None;

But if you read this, you should be able to extract what you need ?

http://msdn.microsoft.com/en-us/library/ms171608.aspx


Before you repopulate, take a note of the sorted column, and afterwards reapply the sort: you might also want to preserve the current selected row, as otherwise it will be lost when you repopulate.

int? index = null;
int firstDisplayedRowIndex = 0;
int sortedColumnIndex = -1;
SortOrder sortOrder = SortOrder.Ascending;

if (dgv.CurrentRow != null)
{
    index = dgv.CurrentRow.Index;
    firstDisplayedRowIndex = dgv.FirstDisplayedScrollingRowIndex;

    if (dgv.SortedColumn != null)
    {
        sortedColumnIndex = dgv.SortedColumn.Index;
        sortOrder = dgv.SortOrder;
    }
}

// Repopulate grid...

if (index.HasValue)
{
    if (sortedColumnIndex > -1)
    {
        switch (sortOrder)
        {
            case SortOrder.Ascending:
                dgv.Sort(dgv.Columns[sortedColumnIndex], ListSortDirection.Ascending);
                break;
            case SortOrder.Descending:
                dgv.Sort(dgv.Columns[sortedColumnIndex],
                                        ListSortDirection.Descending);
                break;
                // SortOrder.None - or anthing else - do nothing
        }
    }

    dgv.Rows[index.Value].Selected = true;
    dgv.Rows[index.Value].Cells[0].Selected = true;
    dgv.FirstDisplayedScrollingRowIndex = firstDisplayedRowIndex;
    // Call any code that needs to know the selection might have changed
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号