Posted on 2010-08-14
I am writing a windows application where in I have designed a search form with datagrid view. When user presses enter key, it captures the primary key of selected row. My code is as given below.
private void dgridaccountnature_KeyPress(object sender, KeyPressEventArgs e)
if (e.KeyChar != (char) Keys.Enter)
GlobalVariable.searchaccountnatureid = "";
if (dgridaccountnature.CurrentRow != null)
dgridaccountnature.Rows[dgridaccountnature.CurrentRow.Index - 1].Cells[0
string message = StandardMessage.DataAccessError;
Example: Let us say I have 3 rows and one blank row in my datagridview, so totally 4 rows inlucluding blank row.
Now when user presses enter key on blank row, it captures the primary key of previous row which is not correct.
For this problem i was suggested to use the following code
if (e.KeyChar != (char) Keys.Enter || dgridaccountnature.CurrentRow.Index == dgridaccountnature.Rows.Count-1)
Now when I use this code, pressing enter on blank row (4th row is solved) but when I press enter on 3rd row having data, nothing happens, i mean it does not capture the primary key id. But only first row it works when i press enter on first row.