Capture DataGridView cell’s KeyPress event

Background

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.

Problem

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

Solution

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
KeyPressEventHandler(txt_KeyPress);
	}
}

void txt_KeyPress(object sender, KeyPressEventArgs e)
{
	MessageBox.Show(e.KeyChar.ToString());
}

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 🙂

Posted in ASP.NET, Programming Language, WPF (Windows Presentation Framework)
  • Syed Zubair

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

  • muhamamd shoaib

    its really helping, thanks for sharing.

    stay blesssed

  • bharat

    Hello,
    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?