Click here to Skip to main content
16,019,152 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Collections;
using System.Timers;
using System.Web.SessionState;


namespace student_management.studpro
{
    public partial class WebForm3 : System.Web.UI.Page
    {
        int TotQus=0, ResultId = 100;
        static int count = 0;
        static int viewradio = 0;
        float sepmarks = 0.0f;
        static float marks = 0.0f, correct = 0.0f;
        int totalSeconds = 0, seconds = 60, minutes = 60, selectedcount = 0, originalcount = 0, crt = 0, wr = 0;

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["aloproConnectionString"].ConnectionString);
        string selected;
        string subject_name, Result = null, UserName = null;
        static String CrtAns = null, ChoiceType = null;
        //string constr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Administrator\\Documents\\alopro.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
        DataTable dt;
        DataSet ds;
        SqlDataAdapter ad;
        static int rowindex = -1;

        protected void Page_Load(object sender, EventArgs e)
        {
            subject_name = Request.QueryString["Subject_name"];
            String oldSelectedSubject = subject_name;
            UserName =(string)Session["UserName"];
            Session["Subject_name"] = oldSelectedSubject;

            string noofqns = "SELECT [Questions] FROM [testsettings]";
            SqlCommand cmd = new SqlCommand(noofqns, con);
            con.Open();
            TotQus = Convert.ToInt16(cmd.ExecuteScalar().ToString());
            ds = new DataSet();

            ad = new SqlDataAdapter("SELECT * FROM addsubject", con);
            ad.Fill(ds,"addsubject");
            dt = ds.Tables["addsubject"];
            con.Close();
            if (viewradio == 0)
            {
                RadioInvisible();
            }
            else
            {
                RadioVisible();
            }
            viewradio += 1;

            CheckBoxInvisible();
        }

        protected void Timer1_tick(object sender, EventArgs e)
        {

            Session["time"] = Convert.ToInt16(Session["time"]) - 1;
            if (Convert.ToInt16(Session["time"]) <= 0)
            {
                
                ButtonNext.Visible = false;
                RadioInvisible();
               
           }
            else
            {
              
                totalSeconds = Convert.ToInt16(Session["time"]);
                seconds = totalSeconds % 60;
                minutes = totalSeconds / 60;
                clock.Text = minutes + ":" + seconds;

            }
        }
        public string SelectedAnswer()
        {
            if (RadioButton1.Checked)
            {
                return "A";
            }
            else if (RadioButton2.Checked)
            {
                return "B";
            }
            else if (RadioButton3.Checked)
            {
                return "C";
            }

            else if (RadioButton4.Checked)
            {
                return "D";
            }
            else
            {
                return "nothing";
            }
        }
        protected string ChooseAnswer()
        {
            string choose=null;

            if (CheckBox1.Checked)
            {
                choose = "A,";
            }
            if (CheckBox2.Checked)
            {
                choose += "B,";
            }
            if (CheckBox3.Checked)
            {
                choose += "C,";
            }
            if (CheckBox4.Checked)
            {
                choose += "D,";
            }
            return choose;
        }
        protected void RadioUncheck()
        {
            RadioButton1.Checked = false;
            RadioButton2.Checked = false;
            RadioButton3.Checked = false;
            RadioButton4.Checked = false;

        }
        protected void CheckBoxUncheck()
        {
            CheckBox1.Checked = false;
            CheckBox2.Checked = false;
            CheckBox3.Checked = false;
            CheckBox4.Checked = false;

        }

        protected void RadioInvisible()
        {
            RadioButton1.Visible = false;
            RadioButton2.Visible = false;
            RadioButton3.Visible = false;
            RadioButton4.Visible = false;

        }
        protected void RadioVisible()
        {
            RadioButton1.Visible = true;
            RadioButton2.Visible = true;
            RadioButton3.Visible = true;
            RadioButton4.Visible = true;

        }
        protected void CheckBoxVisible()
        {
            CheckBox1.Visible = true;
            CheckBox2.Visible = true;
            CheckBox3.Visible = true;
            CheckBox4.Visible = true;
        }

        protected void CheckBoxInvisible()
        {
            CheckBox1.Visible = false;
            CheckBox2.Visible = false;
            CheckBox3.Visible = false;
            CheckBox4.Visible = false;

        }

        protected void ButtonStart_Click(object sender, EventArgs e)
        {
            Response.Write("<script language='javascript'>alert('TimeStarts now');</script>");
            string query = "SELECT [Time] FROM [testsettings]";
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            int timeget = Convert.ToInt16(cmd.ExecuteScalar().ToString());
            totalSeconds = timeget * 60;
            Timer1.Enabled = true;
            Session["time"] = totalSeconds;
            rowindex = rowindex + 1;
            count = count + 1;
            try
            {
                if (rowindex < TotQus)
                {

                    ChoiceType = dt.Rows[rowindex]["ChooseAnswer"].ToString();
                    lblnoofquestions.Text = count.ToString() + "  of  " + TotQus;
                    lblQuestion.Text = dt.Rows[rowindex]["Questions"].ToString();
                    Option1.Text = dt.Rows[rowindex]["Answera"].ToString();
                    Option2.Text = dt.Rows[rowindex]["Answerb"].ToString();
                    Option3.Text = dt.Rows[rowindex]["Answerc"].ToString();
                    Option4.Text = dt.Rows[rowindex]["Answerd"].ToString();
                    CrtAns = dt.Rows[rowindex]["Correctans"].ToString();  
                    if(ChoiceType =="Single")
                    {

                        RadioVisible();
                        CheckBoxInvisible();
                }
                    
                    else
                    {
                        RadioInvisible();
                        CheckBoxVisible();
                        Report();
                    }
                }
                   else
                    {

                        ButtonNext.Visible = false;
                        RadioInvisible();
                        CheckBoxInvisible();
                        marks = (float)(((float)(correct) / (float)(TotQus)) * 100);
                        if (marks >= 50)
                        {
                            Result = "pass";
                        }
                        else
                        {
                            Result = "fail";
                        }
                }
            }

            catch (IndexOutOfRangeException)
            {
                Response.Write("Questions Over");
            }
            finally
            {
                ButtonStart.Visible = false;
                ButtonNext.Visible = true;
                con.Close();
            }
        }

      protected void Report()
        {
            try
            {
                string InsQuery = "INSERT into results VALUES('" + ResultId.ToString() + "','" + UserName + "','" + subject_name + "','" + DateTime.Today + "','" + TotQus + "','" + marks + "','" + Result + "')";
                con.Open();
                SqlCommand cmd2 = new SqlCommand(InsQuery, con);
                cmd2.ExecuteNonQuery();
            }

            catch (Exception ex)
            {
                Response.Write("<Script='javascript'>alert('Tryagain');</script>");
                Response.Write(ex);
            }
            finally
            {
                con.Close();
            }
        }

        protected void ButtonNext_Click(object sender, EventArgs e)
        {
            con.Open();
            count += 1;
            try
            {

                if (rowindex < TotQus)
                {
                    rowindex = rowindex + 1;
                    ChoiceType = dt.Rows[rowindex]["ChooseAnswer"].ToString();
                    lblnoofquestions.Text = count.ToString() + "  of  " + TotQus;
                    lblQuestion.Text = dt.Rows[rowindex]["Questions"].ToString();
                    Option1.Text = dt.Rows[rowindex]["Answera"].ToString();
                    Option2.Text = dt.Rows[rowindex]["Answerb"].ToString();
                    Option3.Text = dt.Rows[rowindex]["Answerc"].ToString();
                    Option4.Text = dt.Rows[rowindex]["Answerd"].ToString();
                    CrtAns = dt.Rows[rowindex]["Correctans"].ToString();
                  
                }
            }
            catch (Exception)
            {
                Response.Write("<script language='javascript'>alert('Wait utill time over');</script>");

            }
            finally
            {
                string select=null;
                  if (ChoiceType == "Single")
            {
                selected = SelectedAnswer();
                if (CrtAns == selected)
                {
                    correct = correct + 1;
                }
            }
            else
                //if (ChoiceType == "multiple")
                {
                    selected = ChooseAnswer();
                  select=Convert.ToString(selected.Remove(selected.Length - 1, 1));
                    ArrayList userSelected = new ArrayList();
                    ArrayList originalvalues = new ArrayList();
                    string[] originalAns = CrtAns.Split(',');
                    string[] str =select.Split(',');

                    foreach (string orignal in originalAns)
                    {
                        originalvalues.Add(orignal);
                    }

                    foreach (string orignal in str)
                    {
                        userSelected.Add(orignal);
                    }

                    selectedcount = userSelected.Count;
                    originalcount = originalvalues.Count;
                    float orgcnt = (float)originalcount;
                    sepmarks = (1.0f) / orgcnt;

                    if (selectedcount > originalcount)
                    {
                        crt = 0;
                        Response.Write(" Crt :" + crt);
                    }
                    else
                    {
                        for (int i = 0; i < selectedcount; i++)
                        {
                            if (originalvalues.Contains(userSelected[i]))
                            {
                                crt += 1;
                           }

                            else
                            {
                                wr += 1;
                            }

                        }
                    }
                    correct += (sepmarks * crt);
                    Response.Write(correct);
                }
        }
                 con.Close();
                 //Server.Transfer("/studpro/onlinetest.aspx");
                RadioUncheck();
                CheckBoxUncheck();
                
            }

        }
Posted
Updated 12-Feb-15 21:38pm
v5
Comments
Tomas Takac 13-Feb-15 2:31am    
On which line does it throw the exception?
Member 11449145 13-Feb-15 3:39am    
select=Convert.ToString(selected.Remove(selected.Length - 1, 1));
Tomas Takac 13-Feb-15 3:59am    
Did you debug the code at all? ChooseAnswer() returns null when none of the checkboxes is checked. You need to handle that case. BTW why do you use Convert.ToString() on a string?
Sergey Alexandrovich Kryukov 13-Feb-15 2:33am    
This is not a question, just code dump. You did not explain what you are trying to achieve and did not indicate where the exception was thrown. This exception is the easiest to locate and fix. Please use the debugger.
—SA
Member 11449145 13-Feb-15 2:38am    
in next button _click()
finally{
select=Convert.ToString(selected.Remove(selected.Length - 1, 1));
this line shows me a use a new keyword to create object instances

1 solution

Your function ChooseAnswer() can return null, which is probably what is causing that exception. Like SA said, you should use debugger to check whenever selected is null or not.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900