Reputation: 596
I'm working on a system that involves entering a group of values into a series of textboxes, and then clicking on a button that adds the value in each textbox into it's respective List<>
.
Once the button has been clicked, I use the Focus()
function to put the focus on the textbox at the top of the group of textboxes (txtHR
). This works fine when the button is clicked on using the cursor.
The only problem is this:
As there are a lot of textboxes to be written in, I made a function where hitting the Enter key moves the focus down the list of textboxes (making data entry quicker). This leads to the focus then being on the button btnSaveData
, and hitting the Enter key again effectively executes the button-click.
This would return the focus to txtHR
, but the system then also takes in the Enter key press and moves the focus down into the next textbox.
Is there a way to correct this? I'm guessing it would involve an if/else
statement based around whether it was the button click or the key press that calls the txtHR.Focus()
.
Code for both, btnSaveData_Click
and Control_KeyUp
, is shown below:
private void btnSaveData_Click(object sender, EventArgs e) //To be clicked while clock is running
{ //turn inputted data into outputted data
//take the data in the input boxes and...
updateLists(); //add to respective list
saveReadings(); //append each variable to file
//return cursor to top box in list ready for next data set
txtHR.Focus();
}
private void Control_KeyUP(object sender, KeyEventArgs e) //for selected textboxes and buttons only
{
if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
{
this.SelectNextControl((Control)sender, true, true, true, true);
}
}
Upvotes: 0
Views: 3059
Reputation: 2363
You could test to make sure the control where the Enter key is pressed is a TextBox
before doing the focus change, or if there are other types of controls where you also want this focus forwarding behavior, instead test if it is the Save button. Something like this:
private void Control_KeyUP(object sender, KeyEventArgs e) //for selected textboxes and buttons only
{
// Bail if not on a TextBox.
if ((sender as TextBox) == null) // **or instead** if ((sender as Button) == this.btnSaveData)
return;
if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
{
this.SelectNextControl((Control)sender, true, true, true, true);
}
}
Upvotes: 1