2
votes

I have a dataGridView control with the SelectionMode property set to CellSelect. I am using the CellBeginEdit & CellEndEdit methods to get the value before & after the edit. In both cases, I have been using the following to get at the cell in question.

dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]

As an example, if I edit the first row, e.RowIndex & e.ColumnIndex are zero in both CellBeginEdit & CellEndEdit. If I press enter to end the edit, the desired cell is right there (row 0, column 0) in CellEndEdit. All of this is expected.

However, if I am editing a column with sorting turned on, and I end my edit by clicking into a cell on another row, the rows are reordered alphabetically before CellEndEdit is called. So, even though the event arguments still contain zero for e.RowIndex & e.ColumnIndex, my edited row may not be at that index.

The row never changes position visually, and setting the column's SortMode property to NotSortable in CellBeginEdit doesn't affect the behavior.

Is this a Microsoft bug or am I missing something? Also, if this behavior is unavoidable, what is the best way to get my edited row in CellEndEdit?

1

1 Answers

2
votes

Well, after trying many different workarounds, I have found one that works:

    private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
    {
        DataGridViewCell cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

        if (cell.IsInEditMode)
        {
            ...
        }
    }

Hope this helps someone else.