0

my project is about online aptitude test system. when i am executing the start exam page the questions are getting displayed but answer is not getting submitted. when i click on the submit button I am getting error on if(ds1.Tables[0].Rows.Count>0) and when i click on the 'previous'button getting error on if(i==ds.Tables[0].Rows.Count-1 || i !=0)

ERROR :- object reference not set to an instance of an object

I can figure out where I am making mistake. Have a look at the code show me where I am making mistake and what is the solution.

.aspx.cs:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

using System.Collections;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class StartExam : System.Web.UI.Page
{
int totalsec = 0, sec = 0, min = 0;
String time = "";
static int j = 0;
static int i,total;
SqlConnection con;
static SqlDataAdapter da,da1;
static DataSet ds,ds1;
SqlCommand cmd;
String date;
String str,str1;

protected void Page_Load(object sender, EventArgs e)
{

    date = DateTime.Now.ToShortDateString();
    con = new SqlConnection("Data Source=.;Initial Catalog=OnlineExam;Integrated Security=True");
    con.Open();

    if (!Page.IsPostBack)
    {
        Session["time"] = 900;
        i = 0;
        total = 0;

        string str = "Select top 15 * from Question_Master where Que_Topic='" + Session["Topic"].ToString() + "' order by newid()";

        SqlDataAdapter da = new SqlDataAdapter(str, con);
        DataSet ds = new DataSet();

        da.Fill(ds, "Question_Master");

        if (ds.Tables[0].Rows.Count > 0)
        {
            DataRow dr;
            while (i < ds.Tables[0].Rows.Count)
            {
                dr = ds.Tables[0].Rows[i];
                // Session["Answer"] = Convert.ToString(Convert.ToInt32(dr["Que_Answer"].ToString()) - 1);

                QueLabel.Text = dr["Que_Question"].ToString();
                OptionRadioButtonList.ClearSelection();
                OptionRadioButtonList.Items.Clear();
                       OptionRadioButtonList.Items.Add(dr["Que_Option1"].ToString());
                OptionRadioButtonList.Items.Add(dr["Que_Option2"].ToString());
                OptionRadioButtonList.Items.Add(dr["Que_Option3"].ToString());
                  OptionRadioButtonList.Items.Add(dr["Que_Option4"].ToString());
                i++;



                //cmd = new SqlCommand("Insert into Temp_Result(TR_Question,TR_Option1,TR_Option2,TR_Option3,TR_Option4,TR_Answer,TR_Id) values('" + ds.Tables[0].Rows[j][2].ToString().Trim() + "','" + ds.Tables[0].Rows[j][3].ToString().Trim() + "','" + ds.Tables[0].Rows[j][4].ToString().Trim() + "','" + ds.Tables[0].Rows[j][5].ToString().Trim() + "','" + ds.Tables[0].Rows[j][6].ToString().Trim() + "','" + ds.Tables[0].Rows[j][7].ToString().Trim() + "'," + Convert.ToInt32(Session["Id"].ToString()) + ")", con);
                //cmd.ExecuteNonQuery();





                // String str1 = "Select top 15 * from Temp_Result where TR_Id=" + Session["Id"].ToString();
                // SqlDataAdapter da1 = new SqlDataAdapter(str, con);
                // DataSet ds1 = new DataSet();

                // da1.Fill(ds1, "Temp_Result");

                // if (ds1.Tables[0].Rows.Count > 0)
                // {
                // DataRow dr1;
                //  while (i < ds.Tables[0].Rows.Count)
                //  {
                //dr1 = ds1.Tables[0].Rows[i];


                  con.Close();

                // }

                // }
            }
        }
    }
}






protected void EndExamButton_Click(object sender, EventArgs e)
{
    Response.Redirect("~\\Result.aspx");
}

protected void Timer1_Tick(object sender, EventArgs e)
{
    Session["time"] = Convert.ToInt16(Session["time"]) - 1;

    if (Convert.ToInt16(Session["time"].ToString()) <= 0)
    {
        Response.Redirect("~\\Result.aspx");
    }
    else
    {
        totalsec = Convert.ToInt16(Session["time"]);
        sec = totalsec % 60;
        min = totalsec / 60;
        time = min + ":" + sec;
        TimerLabel.Text = time;
    }
}
protected void SESubmitButton_Click(object sender, EventArgs e)
{
    try
   {
        if (OptionRadioButtonList.SelectedItem.Text == ds1.Tables[0].Rows[j][6].ToString())
        {
            total++;

        }
        else
        {

            total += 0;

        }
   cmd = new SqlCommand("update Temp_Result set TR_AttemptedAns='" + OptionRadioButtonList.SelectedItem.Text + "' where TR_Question='" + QueLabel.Text + "' and TR_Id=" + Convert.ToInt32(Session["Id"].ToString()) + "", con);
        cmd.ExecuteNonQuery();
    }
    catch (Exception ex)
    { }
    finally
    {
        if (i < ds1.Tables[0].Rows.Count - 1)
        {
            i++;
            OptionRadioButtonList.SelectedIndex = -1;
        }
        else
        {
            Response.Redirect("~\\Result.aspx?total=" + total);
        }
    }

  }

protected void SENextButton_Click(object sender, EventArgs e)
{
    //int i=0;
    //if (i < ds.Tables[0].Rows.Count - 1)
  //  {
        Response.Redirect(Request.RawUrl);
      //  i++;
       /* QueLabel.Text = ds.Tables[0].Rows[i]["Que_Question"].ToString();
        OptionRadioButtonList.Text = ds.Tables[0].Rows[i]["Que_Option1"].ToString();
        OptionRadioButtonList.Text = ds.Tables[0].Rows[i]["Que_Option2"].ToString();
        OptionRadioButtonList.Text = ds.Tables[0].Rows[i]["Que_Option3"].ToString();
        OptionRadioButtonList.Text = ds.Tables[0].Rows[i]["Que_Option4"].ToString(); */         

  //  }


}

protected void SEPreviousButton_Click(object sender, EventArgs e)
{

    if (i == ds.Tables[0].Rows.Count - 1 || i != 0)
    {
        i--;

        /*QueLabel.Text = ds.Tables[0].Rows[i]["Que_Question"].ToString();
        OptionRadioButtonList.Text = ds.Tables[0].Rows[i]["Que_Option1"].ToString();
        OptionRadioButtonList.Text = ds.Tables[0].Rows[i]["Que_Option2"].ToString();
        OptionRadioButtonList.Text = ds.Tables[0].Rows[i]["Que_Option3"].ToString();
        OptionRadioButtonList.Text = ds.Tables[0].Rows[i]["Que_Option4"].ToString();*/
    }

}

protected void OptionRadioButtonList_SelectedIndexChanged(object sender, EventArgs e)
{

    if (ds1.Tables[0].Rows.Count > 0)
   {
        OptionRadioButtonList.Items[2].Enabled = false;
        OptionRadioButtonList.Items[3].Enabled = false;
    }
    else
    {
        OptionRadioButtonList.Items[2].Enabled = true;

        OptionRadioButtonList.Items[3].Enabled = true;
    }


      if (OptionRadioButtonList.SelectedItem.Text == "")
            SESubmitButton.Enabled = true;
       else
            SESubmitButton.Enabled = false;

    }

protected void EndExamButton_Click1(object sender, EventArgs e)
{
    Response.Redirect("~\\Result.aspx?total=" + total);
}


}
Vasudha Dixit
  • 377
  • 8
  • 21

1 Answers1

0

You cannot access a property of an object if the object is null. For instance:

string Foo = null;
Console.WriteLine(Foo.Length); // null reference exception!

This is what is happening in your code, except with a DataTable. I suspect your query returns no results so when you do:

if (ds.Tables[0].Rows.Count > 0)

... the Rows property is null. You cannot access Count on null.

You must do more diligent null checking:

if(ds.Tables != null)
{
    if(ds.Tables[0].Rows != null)
    {
        //now you can be sure you can access `Count`
    {
}

Other observances:

  1. As Henk mentions, the Timer won't work the way you think. This is not a desktop app, it is a stateless client/server app. Once the response is sent to the client you have lost the ability to interact with the session in that way.

  2. The proper way to redirect is:

    Response.Redirect(url, false);
    Context.ApplicationInstance.CompleteRequest();
    
  3. You need to parameterize your queries to protect against SQL Injection and to help prevent syntax errors. I won't clutter up this answer any more with an example, ADO.Net parameter is a very Google-able topic.
  4. Data binding your radio button list would be advantageous over looping and adding.
Crowcoder
  • 11,250
  • 3
  • 36
  • 45