2

I am using the below code for my online quiz using ASP.NET and SQL Server 2008. I need my radio button to return wrong answer if nothing checked after pressing submit.

    <div id="questionsdiv" runat="server" >
        <asp:Label ID="lblalert" runat="server" ForeColor="Red" Font-Size="20px" Visible="false" /><br />            
        <asp:Repeater ID="questionsrpt" runat="server" OnItemDataBound="questionsrpt_ItemDataBound" >
            <ItemTemplate>
                <asp:HiddenField ID="hfID" runat="server" Value='<%# DataBinder.Eval(Container.DataItem, "id")%>' Visible="false" />
                <asp:RequiredFieldValidator ID="rfvquiz" runat="server" Display="Dynamic" ControlToValidate="rbloptions" ValidationGroup="quizvalidation" ForeColor="Red" Text="*" SetFocusOnError="true"/>&nbsp;<asp:Label ID="lblquestion" runat="server" Font-Size="20px" Text='<%# DataBinder.Eval(Container.DataItem, "title")%>' /><br />
                <asp:RadioButtonList ID="rbloptions" runat="server" ValidationGroup="quizvalidation" Font-Size="14px" style="font-weight:bold"/>
            </ItemTemplate>
        </asp:Repeater>
        <asp:Button ID="btnsubmit" runat="server" OnClick="btnsubmit_Click" Text="Submit" ValidationGroup="quizvalidation" />
    </div>

code behind

//quiz answers submitted
    protected void btnsubmit_Click(object sender, EventArgs e)
    {
        SqlDataReader dReader;
        string email = "";
        string name = "";
        string selectedanswer = "";
        string correctanswer = "";
        int questionId = 0;
        int questionscount = 0;
        int correctcount = 0;
        int wrongcount = 0;
        int success = 0;
        ArrayList answersList = new ArrayList();

        Page.Validate();
        if (Page.IsValid)
        {
            email = txtemail.Text.Trim();
            name = txtname.Text.Trim();

            //check if this account has already taken the quiz.
            DataTable accounts = new DataTable();
            SqlCommand checkentrycmd = new SqlCommand("select * from " + quizresponsestable + " where quizid=@quizid and email=@email");
            checkentrycmd.Parameters.AddWithValue("quizid", quizId);
            checkentrycmd.Parameters.AddWithValue("email", email);

            db checkentry = new db();
            accounts = checkentry.returnDataTable(checkentrycmd);

            if (accounts.Rows.Count > 0)
            {
                quizdetails.Visible = false;
                detailsdiv.Visible = false;
                questionsdiv.Visible = false;
                lblmessage.Visible = true;
                lblmessage.Text = "You have already taken this quiz!";
            }
            else
            {
                foreach (RepeaterItem item in questionsrpt.Items)
                {
                    // Checking the item is a data item
                    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                    {
                        //get the questionid
                        var hfId = item.FindControl("hfID") as HiddenField;
                        questionId = Convert.ToInt32(hfId.Value);

                        //get the submitted answer
                        var rdbList = item.FindControl("rbloptions") as RadioButtonList;
                        selectedanswer = rdbList.SelectedValue;
                        //disable to prevent submitting again
                        rdbList.Enabled = false;


                        //get the correct answer
                        SqlCommand getanswercmd = new SqlCommand("select optionid from " + quizquestionanswertable + " where questionid=@questionid");
                        getanswercmd.Parameters.AddWithValue("questionid", questionId);

                        db getanswer = new db();
                        dReader = getanswer.returnDataReader(getanswercmd);

                        if (!dReader.HasRows)
                        {
                            //can't find this question/answer
                        }
                        else
                        {
                            while (dReader.Read())
                            {
                                correctanswer = dReader["optionid"].ToString();
                            }
                        }

                        //compare both answers
                        if (selectedanswer == correctanswer)
                        {
                            correctcount++;
                            rdbList.SelectedItem.Attributes.Add("style", "color: #006400");
                        }
                        else
                        {
                            wrongcount++;
                            rdbList.SelectedItem.Attributes.Add("style", "color: #ff0000");
                            rdbList.Items.FindByValue(correctanswer).Attributes.Add("style", "color: #006400");
                        }

                        //add the submitted answer to list
                        answersList.Add(new string[] { questionId.ToString(), selectedanswer });
                    }
                }

                //create entry
                SqlCommand insertentrycmd = new SqlCommand("insert into " + quizresponsestable + " (quizid, email, name, correctanswers, wronganswers, lastupdated) values (@quizid, @email, @name, @correctanswers, @wronganswers, @lastupdated);SELECT CAST(scope_identity() AS int)");
                insertentrycmd.Parameters.AddWithValue("quizid", quizId);
                insertentrycmd.Parameters.AddWithValue("email", email);
                insertentrycmd.Parameters.AddWithValue("name", name);
                insertentrycmd.Parameters.AddWithValue("correctanswers", correctcount);
                insertentrycmd.Parameters.AddWithValue("wronganswers", wrongcount);
                insertentrycmd.Parameters.AddWithValue("lastupdated", updatedate);

                db insertentry = new db();
                success = insertentry.ReturnIDonExecuteQuery(insertentrycmd);

                //display the result on screen
                if (success > 0)
                {
                    foreach (string[] arr in answersList)
                    {
                        SqlCommand insertresponsecmd = new SqlCommand("insert into " + quizuserreponsetable + " (responseid, questionid, optionid, lastupdated) values (@responseid, @questionid, @optionid, @lastupdated)");
                        insertresponsecmd.Parameters.Clear();
                        insertresponsecmd.Parameters.AddWithValue("responseid", success);
                        insertresponsecmd.Parameters.AddWithValue("questionid", arr[0].ToString());
                        insertresponsecmd.Parameters.AddWithValue("optionid", arr[1].ToString());
                        insertresponsecmd.Parameters.AddWithValue("lastupdated", updatedate);

                        db insertresponses = new db();
                        insertresponses.ExecuteQuery(insertresponsecmd);
                    }

                    detailsdiv.Visible = false;
                    questionscount = correctcount + wrongcount;
                    lblalert.Visible = true;

                    //get the completion description from database table
                    SqlDataReader Treader;
                    SqlCommand getcompletiondesc = new SqlCommand("select completiondescription from " + quizdetailstable + " where id=@quizid");
                    getcompletiondesc.Parameters.AddWithValue("quizid", quizId);

                    db getdesc = new db();
                    Treader = getdesc.returnDataReader(getcompletiondesc);

                    if (!Treader.HasRows)
                    {
                        lblalert.Text = "Thanks for taking the Quiz." + "<br />" + "You have answered <span style='color:#006400;'>" + correctcount + "</span> questions correctly out of " + questionscount + "<br />";
                    }
                    else
                    {
                        while (Treader.Read())
                        {
                            string completiondesc = Treader["completiondescription"].ToString();
                            lblalert.Text = completiondesc + "<br />" + "You have answered <span style='color:#006400;'>" + correctcount + "</span> questions correctly out of " + questionscount + "<br />";
                        }
                    }


                    btnsubmit.Visible = false;
                }
                else
                {
                    lblalert.Visible = true;
                    lblalert.Text = "Sorry! we could not process your request. Please try again.";
                }
            }
        }
        else
        {
            lblalert.Visible = true;
            lblalert.Text = "Please answer all the questions!";
        }
    }
Dale K
  • 25,246
  • 15
  • 42
  • 71
Amer
  • 21
  • 1
  • 1
    Careful, you have a huge injection issue there. `"...from " + quizresponsestable + " where..." is a very very dangerous piece of code. – Thom A Oct 15 '19 at 09:04
  • please can you give more explanation ? – Amer Oct 15 '19 at 09:37
  • [SQL Injection](https://en.wikipedia.org/wiki/SQL_injection) & [Little Bobby Tables](https://xkcd.com/327/) should be all the explanation you need. – Thom A Oct 15 '19 at 09:40

1 Answers1

0

A question that I have is this: If you are starting with an empty string for the SelectedValue, why don't you check the ensure that string.IsNullOrEmpty() fails for the value in question? The Page.IsValid() method will return "true" because, as far as it is concerned, the information that it uses to determine whether the Page is validated is complete.

And this part is free: (IMHO) if you are going to use a ValidationGroup, use a ValidationSummary as well. That way, you don't have to worry about individual labels

  • can you please tell me where i should modify my code. ? – Amer Oct 17 '19 at 06:23
  • Look at where you assign the value of the selected answer. Remember that the value of a radiobuttonlist item is going to be a string. You have to check to find out if you have a value, before you assign it to a variable. – Andrew McFall III Oct 17 '19 at 19:18