Reputation: 1
I have set a question up with a text box for the users answers, once they give an answer i want the text box to be disabled and a label to appear saying either correct or incorrect. But currently only one number can be typed in then the correct or incorrect labels appears. As you can see below the answer is 10. So as soon as 1 is entered, incorrect is displayed and the text box is disabled.
private void txt_2a_TextChanged(object sender, EventArgs e)
{
if (txt_2a.Text == "10")
{
lblcorrectQ2_1.Visible = true;
txt_2a.Enabled = false;
}
else
{
lblincorrectQ2_1.Visible = true;
txt_2a.Enabled = false;
}
}
Upvotes: 0
Views: 67
Reputation: 23732
Why not using ENTER as confirmation that the user is finished typing his/her answer. You can use the KeyDown
event to catch the input and if ENTER was hit validate the input:
private void txt_2a_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
validateAnswer(txt_2a.Text);
}
}
private void validateAnswer(string text)
{
if (text == "10")
{
lblcorrectQ2_1.Visible = true;
}
else
{
lblincorrectQ2_1.Visible = true;
}
txt_2a.Enabled = false;
}
Upvotes: 1
Reputation: 14604
If you don't wan't the users to have to leave the box, you could implement a mechanism where, the first time the TextChanged
event is executed you create a Timer, and tell it to execute an action after the time is up (say 1 second).
If another TextChanged
event happens, you check to see if the Timer
has already been created. If it has, then you call timer.Stop(); timer.Start();
to reset the timer. When the user finally stops typing for 1 second, then the validation can occur.
Note that since the validation is modifying the ui, and the Timer runs on a different thread, you'll probably need to marshal the thread back into the UI thread. Which can be simply done by doing something like this https://stackoverflow.com/a/661706/193282 or this https://stackoverflow.com/a/661662/193282
Upvotes: 0