How to access the Index of a changed Selection in a Datagridview

521 views Asked by At

I am working on a windows form. Currently I am geting quite a headache over a seemingly simple prolbem.

I have a datagridview and want to allow right click selection. Therefore I created a function called dataGridViewJobs_MouseDown that is raised on MouseDown on the datagridview:

private void dataGridViewJobs_MouseDown(object sender, MouseEventArgs e)
{
    int curRowIdx = dataGridViewJobs.HitTest(e.Location.X, e.Location.Y).RowIndex;
    if (curRowIdx != -1 && curRowIdx < dataGridViewJobs.Rows.Count)
    {
        dataGridViewJobs.CurrentCell = dataGridViewJobs[0, curRowIdx];
    }
}

A hitTest is executed to find the row-index of the clicked cell. Afterwards the currentCell of the datagridview is set to the first cell in said row.

This causes the SelectionChanged-event to be raised. This is connected to the following function:

private void dataGridViewJobs_SelectionChanged(object sender, EventArgs e)
{
    if (dataGridViewJobs.Rows.Count > 0)
    {
         Console.WriteLine(dataGridViewJobs.CurrentCell.RowIndex);
    }
 }

This writes the old index to the console. Why is that?

I am currently working with a workaround, which means I save the result of the hitTest in a global variable. But that can not be the right way to do this.

Am I doing something wrong? Thanks in advance!

1

There are 1 answers

0
Fabio On BEST ANSWER

From MSDN

When you change the value of the CurrentCell property, the SelectionChanged event occurs before the CurrentCellChanged event. Any SelectionChanged event handler accessing the CurrentCell property at this time will get its previous value.

Use CurrentCellChanged event for printing current value