Wednesday, December 22, 2010

Making a multi-choice quiz application in Asp.net

I was very interested the quiz that is in w3schools I decided to try to create one in Asp.net.I use a database and Viewstates to manage the quiz .It is very staigtht forward and self explainatory .If you are interested, I can always explain it .


Here is the final view
Database
I use Linq to SQL classes
Finally i create simple Quiz manager to insert,update and delete questions for the quiz.I use a detailsview control because its very optimal for such funtionality


Here is the source code for the quiz i made.
using System;
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{ 
   //create variables you will need to use in the application
    ArrayList quizHistory = new ArrayList();
    QuizDataContext qz = new QuizDataContext();
    int questionNum = 1;
    int score = 0;
    int totalQuestions;
    Random generator;

    protected void Page_Load(object sender, EventArgs e)
    {
        // Load quiz on page load
        if (!Page.IsPostBack) 
        {
            totalQuestions = qz.Quizs.Count();
            LoadQuestion(questionNum);
        }
    }

    void LoadQuestion(int questionNum)
    {
        Quiz myQuiz;
        generator = new Random();
        int ranHolder;
        using (QuizDataContext db = new QuizDataContext())
        {
            myQuiz = (from q in db.Quizs
                      where q.QuestionId == questionNum
                      select q).Single(); // only single instance wanted

            // clear Previos items
            answers.Items.Clear();

            //allocate values to controls
            Label1.Text = myQuiz.Question;
            //random template loader
            ranHolder = generator.Next(1, 4); // Quiz template position is random.
            switch (ranHolder)
            {
                case 1: // template One
                    answers.Items.Add(myQuiz.Answer);
                    answers.Items.Add(myQuiz.Anwer2);
                    answers.Items.Add(myQuiz.CorrectAns);
                    answers.Items.Add(myQuiz.Anwer3);
                    // store key items into the ViewState bag
                    SaveAnswers(myQuiz);
                    break;
                case 2:
                    answers.Items.Add(myQuiz.Answer);
                    answers.Items.Add(myQuiz.CorrectAns);
                    answers.Items.Add(myQuiz.Anwer2);
                    answers.Items.Add(myQuiz.Anwer3);
                    // store key items into the ViewState bag
                    SaveAnswers(myQuiz);
                    break;
                case 3:
                    answers.Items.Add(myQuiz.Answer);
                    answers.Items.Add(myQuiz.Anwer2);
                    answers.Items.Add(myQuiz.Anwer3);
                    answers.Items.Add(myQuiz.CorrectAns);

                    // store key items into the ViewState bag
                    SaveAnswers(myQuiz);
                    break;
                case 4:
                    answers.Items.Add(myQuiz.CorrectAns);
                    answers.Items.Add(myQuiz.Answer);
                    answers.Items.Add(myQuiz.Anwer2);
                    answers.Items.Add(myQuiz.Anwer3);

                    // store key items into the ViewState bag
                    SaveAnswers(myQuiz);
                    break;
            }

        }

    }

    private void SaveAnswers(Quiz myQuiz)
    {    // save to viewstate
        ViewState["CorrectAnswer"] = myQuiz.CorrectAns;
        ViewState["History"] = quizHistory;
        ViewState["QuestionNum"] = myQuiz.QuestionId;
        ViewState["Scores"] = score;
        ViewState["QuestionTotal"] = totalQuestions;
    }
    protected void nextBtn_Click(object sender, EventArgs e)
    {
        // store essental variables in the viewState bag
        quizHistory = (ArrayList)ViewState["History"];
        questionNum = (int)ViewState["QuestionNum"];
        score = (int)ViewState["Scores"];
        totalQuestions = (int)ViewState["QuestionTotal"];


        // check for correct answer
        if (answers.SelectedItem.Value == (string)ViewState["CorrectAnswer"])
        {
            score += 1;
            quizHistory.Add("Correct");
        }
        else
        {
            // add to history
            quizHistory.Add(answers.SelectedItem.Value);
        }

        // Check if end of Quiz
        //if end show results
        if (totalQuestions == questionNum)
        {
            ResultPanel.Visible = true;
            ShowResult();
        }
        else
        {    //Hide result panel
            ResultPanel.Visible = false;
            //Go to next question            
            questionNum += 1;
            // show next question
            LoadQuestion(questionNum);
        }
    }
    void ShowResult()
    {

        Label2.Text = "Score " + score.ToString() + " / 4 ";
        LblCongrats.Text = "

Congratulations!!!

"; if (score == qz.Quizs.Count()) LblCongrats.Visible = true; for (int i = 1; i <= totalQuestions; i++) { lblHistory.Text += i.ToString() + " Choice made was " + quizHistory[i - 1] + " "; } } protected void LoadBut_Click(object sender, EventArgs e) { totalQuestions = qz.Quizs.Count(); LoadQuestion(questionNum); Response.Redirect("Default.aspx"); } }
Happy programming
In my next post i will write the same application using ASP.net MVC ."The only way to learn a framework is to build an application with it".

8 comments:

  1. Hi i was just wondering what Answers were in your example? you haven't included an example of the controls you used in the aspx file? are they a checkboxlist that you databind to?
    Cheers,
    Tom

    ReplyDelete
  2. sorry i meant radiobutton list!

    ReplyDelete
  3. hi could you expalin the view states to me,and what are all the cases about ?? does this program save the users answer,,i was think bout having a progress tracker,so could i like read the users answer then from the database using this program,thanks

    ReplyDelete
    Replies
    1. The ViewState is just a temporal storage component in ASP.net web forms It is a Dictionary object(key/value pair) underneath. It works like a Session object and i use it to monitor the state of the application and I can therefore save answers and give results.You could replace ViewState with the Session object if you want. Goodluck

      Delete
    2. so the users answerr is stored in the database,,could you send me onn some documentation for this project pls

      Delete
  4. hi i am new to asp,net and i would like to use this quiz in my web site,,could you give me a little help in setting it up thanks

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. what is quiz and quizdatacontext class contains ?

    ReplyDelete

Machine learning is the future

I am very enthusiastic about machine learning and the potential it has solve tough problems. Considering the fact that the amount of data we...