3

How to check whether user selected row in datagrid view and this row is not newrow?

I tried so far this but not working as should:

If Not IsNothing(Grid.CurrentRow) And Not Grid.CurrentRow.IsNewRow Then
End If

First statement seems to works ok but when it comes to second it always return false even if I select NewRow

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Where do you use this code and in what way does it not do what it should? – Tim Schmelter Oct 17 '16 at 11:18
  • @TimSchmelter this is under button click event. Second statement always returns false even if I select newRow. –  Oct 17 '16 at 11:40
  • The original post was tagged only by `VB.NET` But since the answer posted by me was in C# and it was accepted by @JimmyJimm I added C# tag also to the question. – Reza Aghaei Oct 17 '16 at 13:22

1 Answers1

2

If you have selected new row, the DataGridView will changes the current row on its OnValidating method. So if you click on Button when you have selected new row, the row remains selected, but the current row will be changed to its previous row.

So instead of checking for current row, if you want to do this check in Click event of a Button, it's better check for SelectedRows:

C#

if (dataGridView1.SelectedRows.Count == 1 &&
    dataGridView1.SelectedRows[0].Index == dataGridView1.NewRowIndex)
    MessageBox.Show("New Row Selected");

VB.NET

If (DataGridView1.SelectedRows.Count = 1 AndAlso _
    DataGridView1.SelectedRows(0).Index = DataGridView1.NewRowIndex) Then
    MessageBox.Show("New Row Selected")
End If

Note: Your provided code in question, will work untill the control is focuded.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398