I have a DataGridView populated with DataTable, have 10 columns. I have a scenario when moving from one row to another when I click on Enter key then I need that row should be selected and need to have that row values.
But here when I select n-th row then it automatically moves to n+1 Row.
Please help me in this...
In Page Load Event:
SqlConnection con =
new SqlConnection("Data Source=.;Initial Catalog=MHS;User ID=mhs_mt;Password=@mhsinc");
DataSet ds = new System.Data.DataSet();
SqlDataAdapter da = new SqlDataAdapter("select * from MT_INVENTORY_COUNT", con);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
Then,
private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (Char)Keys.Enter)
{
int i = dataGridView1.CurrentRow.Index;
MessageBox.Show(i.ToString());
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int i = dataGridView1.CurrentRow.Index;
MessageBox.Show(i.ToString());
}
That's the default behaviour of the DataGridView, and pretty standard in other data grids by 3rd party vendors too.
Here is what happens:
So by the time the enter key is pressed, the current cell has already changed.
You could use the following if you want to get the row that the user was on before the DataGridView changes the row. This should fit in with your existing code (obviously you will need to add the event handler for it):
void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
int i = dataGridView1.CurrentRow.Index;
MessageBox.Show(i.ToString());
}
}
I hope that helps point you in the right direction. Not sure what you are hoping to do here, but hopefully this explains what you are seeing happen.
Add a Class with the following code and modify your GridView designer page i.e.,
this.dataGridView1 = New System.Windows.Forms.DataGridView();
to
this.dataGridView1 = new GridSample_WinForms.customDataGridView();
the class file is:
class customDataGridView : DataGridView
{
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
this.CurrentCell = this[col, row];
return true;
}
return base.ProcessDialogKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
int col = this.CurrentCell.ColumnIndex;
int row = this.CurrentCell.RowIndex;
this.CurrentCell = this[col, row];
e.Handled = true;
}
base.OnKeyDown(e);
}
}
The following solution is simpler and also works:
In the .Designer.cs file:
this.dataGridView1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dataGridView1_KeyDown);
In the code behind file:
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
// Handle event
e.Handled = true;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With