Capture DataGridView cell’s KeyPress event


It was a challenge for me to achieve this. So I took it and completed successfully. The question is what was the challenge.The challenge was to capture the KeyPress event of DataGridView Cell.


How would you achieve this? We can just simply use DataGridView’s KeyPress event and move on. Then how would you do it.


To achieve this we have to handle the EditingControlShowing event of the DataGridView which gives us the inner control that current column is holding, so that we can access the desired column of the grid and subscribe the KeyPress event of the editing control. There are following types of columns in DataGridView

  • DataGridViewButtonColumn
  • DataGridViewCheckBoxColumn
  • DataGridViewComboBoxColumn
  • DataGridViewImageColumn
  • DataGridViewTextBoxColumn
  • DataGridViewLinkColumn

We will see how to access DataGridViewTextBoxColumn and add KeyPress event to the same.

void dgvDemo_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
	TextBox txt = e.Control as TextBox;
	if (txt != null)
		txt.KeyPress += new

void txt_KeyPress(object sender, KeyPressEventArgs e)

Now that was pretty easy, now in case if you want to do it for a particular column then you can access either with column index or with column name.

With column index

int index = dgvDemo.CurrentCell.ColumnIndex;

With column name

string colName = dgvDemo.CurrentCell.OwningColumn.Name;

This would be very useful when accessing the EditingControl so that we can decide the proper type of the control.

Happy coding 🙂

  • Syed Zubair

    Thanku so much its very helpful for me thanku..:)

  • muhamamd shoaib

    its really helping, thanks for sharing.

    stay blesssed

  • bharat

    I have a textbox in a datagrid that is designed using xaml. Can I access the textbox which has been designed in xaml previously in codefile using the events of the datagrid. Please help me

  • Akaash

    in which event we assign the column name or column index?