Reputation: 69
In my C# Windows Forms application I want to navigate between two dateTimePicker
(dateTimePicker1
, dateTimePicker2
) by pressing the Enter key.
When the Form
open focus on dateTimePicker1
and press Enter key then focus dateTimePicker2
and press Enter key focus dateTimePicker1.
I'm trying the below code but it doesn't work:
private void dateTimePicker2_Enter(object sender, EventArgs e)
{
dateTimePicker1.Focus();
}
Upvotes: 2
Views: 1479
Reputation: 1288
The Enter Event is triggered when you enter a control by pressing tab to change focus or clicking into it. If you want to listen for the enter key you need to use the KeyDown Event.
An implementation of the event handling would look like this:
private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) {
dateTimePicker2.Focus();
}
}
private void dateTimePicker2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) {
dateTimePicker1.Focus();
}
}
Upvotes: 2
Reputation: 2465
You should use KeyDown event
private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
dateTimePicker2.Focus();
}
Upvotes: 0
Reputation: 24589
Try this
private void dateTimePicker1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
dateTimePicker2.Focus();
}
}
private void dateTimePicker2_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
dateTimePicker1.Focus();
}
}
Upvotes: 1
Reputation:
The Enter event does not represent the key press of the Enter key, it represents the user changing focus to the control.
https://msdn.microsoft.com/en-us/library/system.windows.forms.control.enter(v=vs.110).aspx
Upvotes: 1