1

I want to get the index of the current row of my DataGridView. The problem is, that if the current row is the new row, CurrentRow is set to the last row that is not the new row. I cannot check for the rows to be selected because if a row is selected that doesn't mean it is the current row and the current row isn't necessarily selected.

I can get the index of the new row, but how can I know whether the new row is the current row?

Ruud
  • 3,118
  • 3
  • 39
  • 51
  • Hi, in some way i understand what you mean but i don't see why you must use currentRow what do you whant to do whith it? Best Regards, Iordan – IordanTanev Aug 16 '09 at 12:19
  • I want to fill a cell of the current row with a value when the user clicks a button. If that row happens to be the new row, this row should be created and the cell should be filled with the value. – Ruud Aug 16 '09 at 12:46

3 Answers3

3

I hooked into the CellClick event via the following code:

private void uiEntries_CellClick(object sender, DataGridViewCellEventArgs e)
{
    Console.WriteLine(e.RowIndex == uiEntries.NewRowIndex);
}

When that condition is true, the user 'selected' the new row. Based upon that information, you may need to actually insert a new record (using the ..Rows.Add() method) before you can actually do anything with it since the new row doesn't actually exist in the collection; it's just there as a placeholder to represent a new row.

Michael Todd
  • 16,679
  • 4
  • 49
  • 69
  • There is one flaw in your solution: when the user changes the current cell not by clicking but by using the keyboard, this won't work. The CurrentCellChanged event will work but this doesn't send a cell. – Ruud Sep 15 '09 at 16:40
  • Then you'll probably have to capture keystrokes as well and see if you should respond to the "movement." For example, if it's a "down arrow" on the next to the last line, that would indicate (perhaps?) that the user is trying to add a row. You could then perform the same steps (inserting new record, etc.) as above. – Michael Todd Sep 15 '09 at 17:14
  • Though it is a lot of hassle, I think this is the solution. Thanks very much! – Ruud Sep 22 '09 at 16:16
0

Can this property value solve your problem?

dataGridView1.CurrentCell.RowIndex

P.K
  • 18,587
  • 11
  • 45
  • 51
0

I use the CellEnter event to save CurrentCell.RowIndex into a form variable. Clicking another button causes this event to fire with the last existing row index instead of the new row index that we need so test for focus to ignore that case.

This avoids having to check for all possible key and mouse actions that might move the cursor to the new row as you do with the CellClick event.

Code auto-converted from VB:

private int ActualCurrentRowIndex;

private void DataGridView1_CellEnter(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
    if (DataGridView1.Focused) {
        ActualCurrentRowIndex = DataGridView1.CurrentCell.RowIndex;
    }
}
user1318499
  • 1,327
  • 11
  • 33