Click here to Skip to main content
16,021,417 members
Please Sign up or sign in to vote.
1.33/5 (3 votes)
See more:
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.

What I have tried:

.aspx.cs

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;
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);
    }
   
     
}
Posted
Updated 7-May-16 5:06am
Comments

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
This question is asked daily and it isn't anything someone can help you with, you need to learn to debug your code

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

Examine the line that is throwing the error in the debugger and see what is null and work out if it's a problem elsewhere or just something you need to code for, eg if ds.Tables[0] is null then do you just treat that the same as it having 0 rows? Or is the issue with your SQL and ds.Tables[0] should never be null. We don't know, only you can know how your code logic is supposed to flow.

Why do I get the error &#8220;Object reference not set to an instance of an object&#8221;? | C# Frequently Asked Questions[^]
 
Share this answer
 
Validate the DataSet object before usage.

  • Check for Null [ ds!=null ]
  • Check the DataSet contains Table(s) [ ds.Tables.Count >0 ]
  • Check the DataSet's Table[n] Contains Rows [ ds.Tables[n].Rows.Count>0 ]

use this code, whenever you are trying to access DataSet Object
C#
 if( ds!=null && ds.Tables.Count >0 && ds.Tables[0].Rows.Count>0) 
{
// Your Code
}


For Theory, Please refer the Solution 1 by OriginalGriff and Solution 4 by Sergey Alexandrovich Kryukov
 
Share this answer
 
v3
Comments
Sergey Alexandrovich Kryukov 7-May-16 11:08am    
5ed. I referenced this solution in Solution 4, where I also explain quite generalized guidelines for debugging.
The answer also really requires explanations on SQL injection; the inquirer's code is vulnerable.
—SA
Karthik_Mahalingam 7-May-16 11:25am    
Thank you Sergey :-)
First, about you SQL query:

Your approach is wrong from the very beginning. The query composed by concatenation with strings taken from UI. Not only repeated string concatenation is inefficient (because strings are immutable; do I have to explain why it makes repeated concatenation bad?), but there is way more important issue: it opens the doors to a well-known exploit called SQL injection.

This is how it works: http://xkcd.com/327.

Are you getting the idea? The string taken from a control can be anything, including… a fragment of SQL code.

What to do? Just read about this problem and the main remedy: parametrized statements: http://en.wikipedia.org/wiki/SQL_injection.

With ADO.NET, use this: http://msdn.microsoft.com/en-us/library/ff648339.aspx.

Please see my past answers for some more detail:
EROR IN UPATE in com.ExecuteNonQuery();,
hi name is not displaying in name?.

Now, about the exception you got.

This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferences by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object".

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx,
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx.

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx.

For the suggestions on your case, please see Solution 3.

Good luck,
—SA
 
Share this answer
 
v2
Comments
Karthik_Mahalingam 7-May-16 11:12am    
5,Bookmarked :-)
You shall post this as an article. Neat and clear explanation.
Sergey Alexandrovich Kryukov 7-May-16 11:33am    
Thank you, Karthik.
My unpublished articles wait in line, I have more unfinished ones than published...
—SA

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