获取错误: - 未将对象引用设置为对象的实例 [英] Getting error :- object reference not set to an instance of an object

查看:108
本文介绍了获取错误: - 未将对象引用设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目是关于在线资质测试系统。当我执行开始考试页面时,问题会显示但是答案没有提交。当我点击提交按钮时,我收到错误if(ds1.Tables [0] .Rows.Count> 0),当我点击'previous'按钮获取错误if if(i == ds.Tables [0 ] .Rows.Count-1 || i!= 0)



错误: - 对象引用未设置为对象实例



我可以弄清楚我犯错的地方。看看代码告诉我我在哪里犯了错误,解决方案是什么。



我尝试了什么:



.aspx.cs



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

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);
    }
   
     
}

推荐答案

这是最常见的问题之一我们被问到,这也是我们最不能回答的问题,但是你最有能力回答自己。



我来解释一下错误的含义:您已尝试使用变量,属性或方法返回值,但它包含null - 这意味着变量中没有类的实例。

它有点像口袋:你你的衬衫上有一个口袋,用来握笔。如果你进入口袋并发现那里没有笔,你就不能在一张纸上签名 - 如果你尝试的话,你会得到非常有趣的外观!空口袋给你一个空值(这里没有笔!)所以你不能做任何你检索笔通常做的事情。它为什么空?这就是问题 - 可能是你今天早上离开家时忘了拿起你的笔,或者你昨晚把它拿到昨天的衬衫口袋里时可能会把笔留下来。



我们无法分辨,因为我们不在那里,更重要的是,我们甚至看不到你的衬衫,更不用说口袋里的东西了!



回到计算机,你做了同样的事情,不知何故 - 我们看不到你的代码,更不用说运行它了,找不到包含null的东西。

但是你可以 - 而Visual Studio将在这里帮助你。在调试器中运行您的程序,当它失败时,VS将向您显示它发现问题的行。然后,您可以开始查看它的各个部分,以查看哪个值为null,并开始回顾代码以找出原因。因此,在包含错误行的方法的开头放置一个断点,然后从头再次运行程序。这一次,VS会在错误发生前停止,让你通过查看代码来查看你的价值来检查发生了什么。



但我们做不到那 - 我们没有您的代码,如果我们拥有它,我们不知道如何使用它,我们没有您的数据。所以尝试一下 - 看看你能找到多少信息!
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!


这个问题每天都会被问到,这不是别人可以帮你的,你需要学习调试你的代码



在Visual Studio 2010中掌握调试 - 初学者指南 [ ^ ]



检查在调试器中抛出错误的行,看看什么是null和工作如果它在其他地方是一个问题或者只是你需要编码的东西,例如,如果ds.Tables [0]为null那么你是否只把它与0行相同?或者是你的SQL和ds.Tables [0]的问题永远不应该是null。我们不知道,只有你可以知道代码逻辑应该如何流动。



为什么我会收到错误&#8220;对象引用未设置为对象的实例&#8221;? | C#常见问题解答 [ ^ ]
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[^]


验证 DataSet 使用前的对象。



  • 检查 [ ds!= null ]
  • 检查DataSet 包含 [ ds.Tables.Count> 0 ]
  • 检查DataSet的表[n] 包含 [ ds.Tables [n] .Rows.Count> 0 ]
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 ]
 if( ds!=null && ds.Tables.Count >0 && ds.Tables[0].Rows.Count>0) 
{
// Your Code
}





理论上,请参阅解决方案1 ​​ Sergey Alexandrovich Kryukov


这篇关于获取错误: - 未将对象引用设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆