Reputation: 1411
I am making a mini test and I am not sure how to go about making a running score that will update the current score after the user submits the test. The score can fluctuate by 25 points depending on if the question goes from wrong to right, and vice versa.
public partial class _Default : System.Web.UI.Page
{
private int totalScore = 0;
public void IncrementScore()
{
totalScore += 25;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblHeader.Text = "quiz not taken";
}
else
{
lblHeader.Text = "Score: " + totalScore;
}
}
protected void Submit_Click(object sender, EventArgs e)
{
/***************************************************************************/
if (IsValid)
if (txtAnswer.Text.Equals("primary", StringComparison.InvariantCultureIgnoreCase))
{
lblQuestionResult1.ForeColor = System.Drawing.Color.Green;
lblQuestionResult1.Text = "Correct";
}
else
{
lblQuestionResult1.ForeColor = System.Drawing.Color.Red;
lblQuestionResult1.Text = "Incorrect";
}
/***************************************************************************/
if (ddList.SelectedItem.Text.Equals("M:N"))
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Green;
lblQuestionResult2.Text = "Correct";
}
else
{
lblQuestionResult2.ForeColor = System.Drawing.Color.Red;
lblQuestionResult2.Text = "Incorrect";
}
/***************************************************************************/
if (RadioButton4.Checked == true)
{
lblQuestionResult3.ForeColor = System.Drawing.Color.Green;
lblQuestionResult3.Text = "Correct";
}
else
{
lblQuestionResult3.ForeColor = System.Drawing.Color.Red;
lblQuestionResult3.Text = "Incorrect";
}
/***************************************************************************/
lblQuestionResult4.ForeColor = System.Drawing.Color.Red;
lblQuestionResult4.Text = "Incorrect";
if (Answer2.Checked && Answer3.Checked && !Answer1.Checked && !Answer4.Checked)
{
lblQuestionResult4.ForeColor = System.Drawing.Color.Green;
lblQuestionResult4.Text = "Correct";
}
}
}
Upvotes: 0
Views: 1286
Reputation: 616
Modify it to something like see, check syntax, was not using VS
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack)
{
lblHeader.Text = "quiz not taken";
}
else
{
Session["TotalScore"] = ""+totalScore; //Storing it in a session
lblHeader.Text = "Score: " + Session["TotalScore"];
}
}
//increment method
if(Session["TotalScore"]!=null)
{
totalScore += 25;
}
else
{
totalScore=int.Parse(Session["TotalScore"])+25;
}
Upvotes: 0
Reputation: 150108
The approach of incrementing
private int totalScore = 0;
will not work because you get a new instance of _Default
for every HTTP request.
You can keep your running score in Session
.
However, I would instead suggest always recalculating the total score when needed by looping through the answers and score associated with each answer as needed. This simplifies the logic if people go back and change an answer (assuming it is permitted to do that).
Upvotes: 2