Display current attempt Quiz Question in Label using C# and VB.Net in ASP.Net

Last Reply one year ago By pandeyism

Posted one year ago

Dear All,

I'm following the below url for Random questions order

https://www.aspforums.net/Threads/350172/Random-Questions-order/Replies/3#Replies

But the order in displaying the total questions as below

Q1 of 20 

for the above format i'm using the below code  

Label1.Text = "Q" + questionid.ToString();

But its displaying the current question id  Q6 of 20 

how can i display Q1 of 20 

for next question when clicking next buuton event

Q2 of 20

 

...............

and up to 20 questions in datatable

Thanks

Posted one year ago Modified on one year ago

Hi irshad1231,

Refer below sample.

HTML

<div>
    <asp:Label ID="Label1" runat="server"></asp:Label>
    of 30
    <div id="dvQuestion" runat="server">
        <h1>
            <asp:Label ID="lblQuestion" runat="server" />
            <asp:HiddenField runat="server" ID="hfQuestionId" />
        </h1>
        <asp:RadioButtonList ID="rbtnOptions" runat="server">
        </asp:RadioButtonList>
        <br />
        <asp:Button ID="btnNext" Text="Next" runat="server" OnClick="Next" />
    </div>
    <div id="dvResult" runat="server" visible="false">
        <h1>
            <asp:Label ID="lblResult" runat="server" />
        </h1>
    </div>
</div>

Namespaces

C#

using System.Configuration;
using System.Data.SqlClient;
using System.Data;

Code

C#

private DataTable DataTableQuestions
{
    get { return (DataTable)ViewState["Questions"]; }
    set { ViewState["Questions"] = value; }
}
private int Score
{
    get { return (int)ViewState["Score"]; }
    set { ViewState["Score"] = value; }
}
private int Count
{
    get { return (int)ViewState["Count"]; }
    set { ViewState["Count"] = value; }
}
static int QuestionId;
static int attemptCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Score = 0;
        QuestionId = 1;
        Count = 1;
        DataTableQuestions = PopulateQuestions();
        GetCurrentQuestion(Convert.ToInt32(DataTableQuestions.Rows[QuestionId - 1]["QuestionId"]), PopulateQuestions());
    }
    Label1.Text = "Q" + Count.ToString();
}
protected void Next(object sender, EventArgs e)
{
    if (QuestionId <= DataTableQuestions.Rows.Count)
    {
        if (rbtnOptions.SelectedIndex != -1)
        {
            string otionSelected = rbtnOptions.SelectedItem.Text.Trim();
            string correctAnswer = CorrectAnswer(Convert.ToInt32(hfQuestionId.Value));

            if (otionSelected.ToLower() != correctAnswer.ToLower())
            {
                attemptCount++;
            }
            else
            {
                attemptCount = 0;
            }
            if (attemptCount >= 1)
            {
                ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Answer is Wrong. Try Again')", true);
            }
            else
            {
                QuestionId++;
                if (otionSelected.ToLower() == correctAnswer.ToLower())
                {
                    Score++;
                    Count++;
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "", "alert('Answer is Correct')", true);
                }
                GetCurrentQuestion(QuestionId, DataTableQuestions);
                attemptCount = 0;
            }
        }
    }
}

private void GetCurrentQuestion(int questionId, DataTable dtQuestions)
{
    if (QuestionId <= dtQuestions.Rows.Count)
    {
        lblQuestion.Text = dtQuestions.Rows[questionId - 1]["QuestionDescription"].ToString();
        hfQuestionId.Value = dtQuestions.Rows[questionId - 1]["QuestionId"].ToString();
        DataTable dtOptions = PopulateOptions(Convert.ToInt16(hfQuestionId.Value));
        List<ListItem> options = new List<ListItem>();
        for (int i = 0; i < dtOptions.Rows.Count; i++)
        {
            options.AddRange(new ListItem[] { new ListItem(dtOptions.Rows[i][1].ToString(), i.ToString()) });
        }
        rbtnOptions.Items.Clear();
        rbtnOptions.Items.AddRange(options.ToArray());
        rbtnOptions.DataBind();
        Label1.Text = "Q" + Count.ToString();
    }
    else
    {
        dvQuestion.Visible = false;
        dvResult.Visible = true;
        lblResult.Text = string.Format("You Scored {0}/{1}", Score, QuestionId - 1);
        Label1.Text = "Q" + (Count - 1).ToString();
    }
}

private DataTable PopulateQuestions()
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT QuestionId,QuestionDescription,'' AnswerSelected FROM QuestionTable ORDER BY NEWID()", con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                con.Open();
                da.Fill(dt);
                con.Close();
            }
        }
    }
    return dt;
}

private DataTable PopulateOptions(int questionId)
{
    DataTable dt = new DataTable();
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT QuestionId,Options FROM OptionTable WHERE QuestionId = @QuestionId", con))
        {
            cmd.Parameters.AddWithValue("@QuestionId", questionId);
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                con.Open();
                da.Fill(dt);
                con.Close();
            }
        }
    }
    return dt;
}

private string CorrectAnswer(int questionId)
{
    string answer = "";
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT Answer FROM AnswerTable WHERE QuestionId = @QuestionId", con))
        {
            cmd.Parameters.AddWithValue("@QuestionId", questionId);
            con.Open();
            answer = cmd.ExecuteScalar().ToString();
            con.Close();
        }
    }
    return answer;
}