Search code examples
c#winformsdatagridviewdatagridviewimagecolumn

DataGridView ImageColumn Handle "Enter" key to perform Click


How to fire Click event of DataGridViewImageColumn when I press Enter. Currently when I press the Enter key on DataGridViewImageColumn it moves to next cell.

enter image description here

Please help.


Solution

  • You can put the code that you want to run in CellContentClick in a method and then on both CellContentClick and KeyDown call that method.

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        if (e.RowIndex >= 0 && e.ColumnIndex== 3)
            DoSomething(e.RowIndex, e.ColumnIndex);
    }
    
    public void DoSomething(int row, int column)
    {
        MessageBox.Show(string.Format("Cell({0},{1}) Clicked", row, column));
    }
    
    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        var cell = this.dataGridView1.CurrentCell;
        if (cell != null && e.KeyCode == Keys.Enter &&
            cell.RowIndex >= 0 && cell.ColumnIndex == 3)
        {
            DoSomething(cell.RowIndex, cell.ColumnIndex);
            e.Handled = true;
        }
    }