WinForm - DataGrid - Enter Key

G

Guest

For a Data Grid in a Win Form, when the user selects a row and then presses
the Enter key, how do I capture that the user pressed the enter key?
 
K

Kevin Yu [MSFT]

Hi,

First of all, I would like to confirm my understanding of your issue. From
your description, I understand that you need to know how to handle the key
press event in a DataGrid. If there is any misunderstanding, please feel
free to let me know.

This depends on how your datagrid looks like. If the selection is to the
whole row (The whole row is highlighted), you can handle the
DataGrid.KeyDown event to achieve this.

private void dataGrid1_KeyDown(object sender,
System.Windows.Forms.KeyEventArgs e)
{
if(e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter key pressed");
}
}

When the focus is in a datagrid cell, the above keydown event will not get
fired. We need to do the following:

Add this line in InitializeComponent(),

this.dataGrid1.ControlAdded +=new
ControlEventHandler(dataGrid1_ControlAdded);

Then add this:

private void dataGrid1_ControlAdded(object sender, ControlEventArgs e)
{
e.Control.KeyDown +=new KeyEventHandler(Control_KeyDown);
}

private void Control_KeyDown(object sender, KeyEventArgs e)
{

}

However, in this case, we can use the above method to handle all the key
event except the Enter key and some other control keys. Because the event
is NOT fired when Enter key is pressed. This is by design. So I suggest you
stick to the first method to handle DataGrid.KeyDown event.

HTH.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."
 
G

Guest

How do I force the Data Grid to only select rows and not select cells? If
the user can only select rows this will work for me because I'm using the
Data Grid to show available License Dealers to select from.

Thanks for your last response, it was easy to understand and worked. If
only I can set the Data Grid to select rows only then it will be perfect.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top