DataGridView "Enter" key event processing

I have a DataGridView populated with a DataTable, has 10 columns. I have a script when switching from one line to another, when I press the Enter key, then I need this line to be selected and it needs to have the values โ€‹โ€‹of this line.

But here, when I select the nth row, it automatically goes into n + 1 Row.

Please help me with this ...

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());
}
+4
source share
2 answers

This is the default behavior of the DataGridView and is pretty standard on other third-party data networks.

Here's what happens:

  • User presses enter
  • DataGridView KeyPress (, ..), .
  • DataGridView , - , .

, .

, , , DataGridView . (, ):

void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        int i = dataGridView1.CurrentRow.Index;
        MessageBox.Show(i.ToString());
    }     
}

, . , , , , , .

+3

GridView, ..

this.dataGridView1 = New System.Windows.Forms.DataGridView();

this.dataGridView1 = new GridSample_WinForms.customDataGridView();

:

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);
  }
}
+2

Source: https://habr.com/ru/post/1527661/


All Articles