如何解决nullreferenceexception的错误 [英] how to solve error of nullreferenceexception

查看:83
本文介绍了如何解决nullreferenceexception的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public partial class Exam : System.Web.UI.Page
{
   SqlConnection cnn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Maulik\Desktop\template\template\App_Data\Database.mdf;Integrated Security=True;User Instance=True");

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            get_T_No();
        }
        if (!IsPostBack)
        {
            start_exam();
        }
        // Label5.Text = Session["S_Id"].ToString();

    }

    protected Boolean check(int i)
    {
      cnn.Open();
      SqlCommand cmd = new SqlCommand("select * from Exam_Details where queid='" + i + "'", cnn);
      SqlDataAdapter da = new SqlDataAdapter();
      DataSet ds = new DataSet();
      da.SelectCommand = cmd;
      da.Fill(ds);
      cnn.Close();
      int c = ds.Tables[0].Rows.Count;
      if (c == 0)
      {
         return false;
      }
      else
      {
         return true;
       }
   }
      
   private void data_bind()
   {
     cnn.Open();
     lblque.Visible = true;
     rbtnans_1.Visible = true;
     rbtnans_2.Visible = true;
     rbtnans_3.Visible = true;
     rbtnans_4.Visible = true;
     btnne.Visible = true;
     btnre.Visible = true;
     lbla.Visible = true;
     lblb.Visible = true;
     lblc.Visible = true;
     lbld.Visible = true;
     cnn.Close();
     while (!check(Convert.ToInt32(Session["i"].ToString())))
     {
        Session["i"] = Convert.ToInt32(Session["i"].ToString()) + 1;
     }

     cnn.Open();
     SqlCommand cmd = new SqlCommand("select queid,sub_que,que_ans1,que_ans2,que_ans3,que_ans4 from Exam_Details where queid='" + Session["i"].ToString() + "' and subid='" + Session["subid"].ToString() + "'", cnn);
     SqlDataReader dr = cmd.ExecuteReader();
     while (dr.Read())
     {
        HiddenField1.Value = dr.GetValue(0).ToString();
        lblque.Text = dr.GetValue(1).ToString();
        rbtnans_1.Text = dr.GetValue(2).ToString();
        rbtnans_2.Text = dr.GetValue(3).ToString();
        rbtnans_3.Text = dr.GetValue(4).ToString();
        rbtnans_4.Text = dr.GetValue(5).ToString();
      }
      dr.Close();
      cnn.Close();

    }


        protected void btnne_Click(object sender, EventArgs e)
        {

            btnne.Visible = false;
            Session["queid"] = HiddenField1.Value.ToString();

            Session["que_ans"] = "";
            if (rbtnans_1.Checked == true)
            {
                Session["que_ans"] = rbtnans_1.Text.ToString();
            }
            else if (rbtnans_2.Checked == true)
            {
                Session["que_ans"] = rbtnans_2.Text.ToString();

            }
            else if (rbtnans_3.Checked == true)
            {
                Session["que_ans"] = rbtnans_3.Text.ToString();
            }
            else if (rbtnans_4.Checked == true)
            {
                Session["que_ans"] = rbtnans_4.Text.ToString();
            }

            if (Session["queid"] != null && Session["que_ans"] != null)
            {

                cnn.Open();
                string str = "insert into Result_Details(candidateid,queid,subid,que_ans,t_no) values('" + Session["candidateid"].ToString() + "','" + Session["queid"].ToString() + "','" + Session["subid"].ToString() + "','" + Session["que_ans"].ToString() + "','" + Session["t_no"].ToString() + "') "; //error line
                SqlCommand cmd = new SqlCommand(str, cnn);
                cmd.ExecuteNonQuery();
                cnn.Close();

            }

            int tot = 0;

            cnn.Open();
            //string Total = "select count(*) from Exam_Detail where T_Id='" + Session["T_Id"].ToString() + "' ";
            string Total = " select top 1 queid from Exam_Details where subid= '" + Session["subid"].ToString() + "' order by queid desc ";
            SqlCommand cmd2 = new SqlCommand(Total, cnn);
            SqlDataReader dr2 = cmd2.ExecuteReader();
            dr2.Read();
            tot = Convert.ToInt32(dr2.GetValue(0));
            dr2.Close();
            cnn.Close();


            if (Convert.ToInt32(Session["i"]) == tot)
            {
                btnne.Visible = false;
                lblque.Visible = false;
                rbtnans_1.Visible = false;
                rbtnans_2.Visible = false;
                rbtnans_3.Visible = false;
                rbtnans_4.Visible = false;
                btnre.Visible = true;
                lbla.Visible = false;
                lblb.Visible = false;
                lblc.Visible = false;
                lbld.Visible = false;
            }
            else
            {
                rbtnans_1.Checked = false;
                rbtnans_2.Checked = false;
                rbtnans_3.Checked = false;
                rbtnans_4.Checked = false;
                Session["i"] = Convert.ToInt32(Session["i"]) + 1;
                string amit = Session["i"].ToString();
                data_bind();
            }

        }
        protected void btnre_Click(object sender, EventArgs e)
        {
            Response.Redirect("Results.aspx");
        }


        private void get_T_No()
        {
            Session["t_no"] = "";

            cnn.Open();
            string str = "select top 1 t_no from Result_Details order by t_no desc ";
            SqlCommand cmd = new SqlCommand(str, cnn);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                Session["t_no"] = dr.GetValue(0).ToString();
            }
            dr.Close();
            if (Session["t_no"] == "")
            {
                Session["t_no"] = "1";
                Response.Write(Session["t_no"].ToString());
            }
            else
            {
                Session["t_no"] = Convert.ToInt32(Session["t_no"]) + 1;
                Response.Write(Session["t_no"].ToString());
            }
            cnn.Close();
        }

        protected void start_exam()
        {

            string id = "";


            cnn.Open();
            SqlCommand cmd = new SqlCommand("select top 1 queid from Exam_Details where subid='" + Session["subid"].ToString() + "'", cnn); //error line
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                id = dr.GetValue(0).ToString();
            }
            dr.Close();
            cnn.Close();

            Session["i"] = Convert.ToInt32(id);
            rbtnans_1.Checked = false;
            rbtnans_2.Checked = false;
            rbtnans_3.Checked = false;
            rbtnans_4.Checked = false;
            data_bind();

        }
    }

推荐答案

问题似乎是 Session [ subid]。ToString()在您的代码中为空。因此,当你传递它时,它会抛出此错误,告诉你这个变量是null并且无法在null上生成SqlCommand。



你可以自己解决这个问题,null,实际上是新开发人员必须面对的一种非常基本的错误。这意味着变量实际上不存在于上下文中(精确的内存)。



有很多帖子你可以阅读,答案是一样的,你需要将变量的值初始化为任何值,但不是空值。



这可能会这样做,



The problems seem like Session["subid"].ToString() is null in your code. So when you pass it, it throws this error telling you that this variable is a null and the SqlCommand cannot be generated on a null.

You can fix this issue yourself, null, actually is a very basic kind of error that new developers have to face. It means that the variable actually doesn't exist in the context (memory to be precise).

There are many posts that you can read and the answer is same, You need to initialize the variable's value to be anything, but not a null value.

This might do,

if(Session["subid"] != null) {
   // check the value, if its not a null,  
   // continue
   SqlCommand cmd = new SqlCommand("select top 1 queid from Exam_Details where subid='" + Session["subid"].ToString() + "'", cnn);
} else {
  // otherwise, show a custom error.
}





阅读这个 [ ^ 。您可能能够理解,这个错误是什么,如何解决它以及如何阻止它再次发生。



祝你好运!



Read this[^] technical blog post of mine. You might be able to understand, what this error is, how to solve it and how to stop it from occuring again.

Good luck!


根据您的异常发生行,您寻找的会话值似乎为null。您可以通过下面的验证来避免异常,但在进入此方法之前检查此会话值为何为空,您可能忘记为此设置值。

according to your exception occurring line, it seems session value that you looking for is null. you can avoid exception by putting validation like below but check why this session value is null before coming to this method, you may have forgot to set value for that.
protected void start_exam()
{
    if(Session["subid"] !=null)
    {
        // your code...

    }
}


if (!IsPostBack)
      {
          start_exam();
      }



您如何看待会话[subid] 收到一个值,如果它是第一次加载该页面?如果(IsPostBack),它必须是


How do you think Session["subid"] received a value if it is the first time that that page is loaded? It must be if (IsPostBack) instead.


这篇关于如何解决nullreferenceexception的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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