Timer control, how to use it for a countdown.

Jun 8 2007 6:02 PM
I am working on an exercise in the book i am using to learn programming and C#, its a math game, i have added a timer so it would let 30 seconds to answer. What i would like to do, is to show that timer (the countdown) is a text box.

I dont know if it is the easiest or best way but, what i though, was to add a while loop, what I set to 30 and dercrmenting at every ticks (setting the timer at 1 sec). Here is my code without that feature. ( I know i could had use Switch for some of the if but, i am not there yet in the book. The countdown is not part of the book, it's just an idea i got)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Math_Game

{
public partial class Form1 : Form

{
Random randomNo = new Random();
int no1, no2;
string problemType = "+";

public Form1()
{
InitializeComponent();
}

private void StartGame_Click(object sender, EventArgs e)
{
timerReset();
StartGame.Visible =
false;
CheckAnswer.Visible =
true;
Question.Visible =
true;
Answer.Visible =
true;
NextQuestion.Visible =
true;
Feedback.Visible =
true;
Gen_Question();
}

private void Gen_Question()
{
no1 = randomNo.Next(100);
no2 = randomNo.Next(100);

if
(radioButton1.Checked)
{
problemType =
"+";
}

else if (radioButton2.Checked)
{
problemType =
"-";
}

else if (radioButton3.Checked)
{
problemType =
"*";
}

Question.Text = no1 + problemType + no2 + "=";
}

private void CheckAnswer_Click(object sender, EventArgs e)

{
timer1.Stop;
int result = 0;

if (problemType == "+")
{
result = no1 + no2;
}

else if (problemType == "-")
{
result = no1 - no2;
}

else if (problemType == "*")
{
result = no1 * no2;
}

if (Answer.Text == result.ToString())
{
Feedback.Text =
"Correct";
}

else
{
Feedback.Text =
"Incorrect";
}
}

private void NextQuestion_Click(object sender, EventArgs e)

{
Gen_Question();
timerReset();
Answer.Visible =
true;
Answer.Text =
"";
Feedback.Text =
"";
}

private void timer1_Tick(object sender, EventArgs e)

{
Answer.Visible =
false;
Feedback.Text =
"Trop tard";
timer1.Stop;
}

private void timerReset()

{
timer1.Interval = 30000;
timer1.Start();
}

}

}


Answers (11)