错误-System.NullReferenceException:对象引用未设置为对象的实例 [英] ERROR - System.NullReferenceException: Object reference not set to an instance of an object

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

问题描述

对象引用未设置为对象的实例.

说明:执行当前Web请求期间发生未处理的异常.请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息.
异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例.
源错误:

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:

Line 47:         //}
Line 48:         //Profile.SCart.Insert(ProductID, Price, 1, ProductName, ProductImageUrl);
Line 49:         SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["techdata"].ToString());
Line 50:         SqlCommand cmd = new SqlCommand();
Line 51:         try



原始代码为:



The orignal code is:

public partial class ProductDetails : System.Web.UI.Page
{
    //string yourname = TextBox1.Text.ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["cart"] != null && Session["cart"] != "")
        {
            yourname.Visible = false;
        }
        else
        {
            yourname.Visible = true;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        
        double Price = double.Parse(((Label)DataList1.Controls[0].FindControl("PriceLabel")).Text);
        string ProductName = ((Label)DataList1.Controls[0].FindControl("NameLabel")).Text;
        string ProductImageUrl = ((Label)DataList1.Controls[0].FindControl("ImageUrlLabel")).Text;
        string ProductID = ((HiddenField)DataList1.Controls[0].FindControl("HiddenField1")).ToString();
        //int ProductID;
        //if (Request.QueryString["ProductID"] != null) 
        //    ProductID = int.Parse(Request.QueryString["ProductID"].ToString());
        //if (Profile.SCart == null)
        //{
        //    Profile.SCart = new ShoppingCartExample.Cart();
        //    //Session["cart"] = SCart;
        //}
        //if (Session["cart"] != null)
        //{
        //    ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE=''javascript''>alert(''CArt is available'');</script>");
        //}
        //Profile.SCart.Insert(ProductID, Price, 1, ProductName, ProductImageUrl);
        SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["techdata"].ToString());
        SqlCommand cmd = new SqlCommand();
        try
            {
            conn.Open();
            cmd = conn.CreateCommand(); 
            if (cmd != null) { cmd.Dispose(); }
            cmd.CommandText = "INSERT INTO cart (ProductID,CustomerName, ProductName, " +
            "ProductImage, ProductPrice) VALUES (''" + ProductID + "'',''" + yourname.Text.ToString() + "'',''" + ProductName + "'',''" +
            ProductImageUrl + "'',''" + Price + "'')";
            cmd.ExecuteNonQuery();
            conn.Close();
            Response.Redirect("~/Admin_Control/UpdateProductInfo.aspx");
            }
        catch (Exception ex)
        {
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE=''javascript''>alert(''" + ex.ToString() + "'');</script>");

        }
        //ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE=''javascript''>alert(''Product added successfully'');</script>");
        Session["cart"] = yourname.Text.ToString();
        Server.Transfer("product.aspx");
    }
}

推荐答案

让我猜:应用程序设置中没有techdata吗?
Let me guess: There is no techdata in the application settings?


基于PageLoad和Button1_Click方法,可能出现此错误的地方:

1. 您在此处进行编码的方式-逻辑错误:

Based on the PageLoad and Button1_Click methods, possible places for this error:

1. The way you had coded here - LOGICAL mistake:

if (cmd != null) { cmd.Dispose(); }
    cmd.CommandText = &quot;INSERT INTO cart (ProductID,CustomerName, ProductName, &quot; +
            &quot;ProductImage, ProductPrice) VALUES ('&quot; + ProductID + &quot;','&quot; + yourname.Text.ToString() + 
&quot;','&quot; + ProductName + &quot;','&quot; +
            ProductImageUrl + &quot;','&quot; + Price + &quot;')&quot;;



如果有命令 cmd ,则继续执行处置" .之后,您继续执行.每次创建命令时,都将其处置,然后尝试访问相同的"cmd"以执行Sql.
您应该对此类sql命令和事务使用try-catch-finally.最后检查cmd值以将其处置.


2.这是基于所使用的硬编码字符串- TYPO 错误,如果其中不存在任何字符串,则在运行时会出现错误:



If there is a command cmd, you go ahead and ''Dispose'' it. After that you continue your execution. Every time you create command you dispose it and then try to access the same ''cmd'' for Sql execution.
You should use, try-catch-finally for such sql commands and transactions. In finally check for the cmd value to dispose it.


2. This is based on the hardcoded strings used - TYPO mistake, if any of them are not existing then you get an error at runtime:

double Price = double.Parse(((Label)DataList1.Controls[0].FindControl("PriceLabel")).Text);
        string ProductName = ((Label)DataList1.Controls[0].FindControl("NameLabel")).Text;
        string ProductImageUrl = ((Label)DataList1.Controls[0].FindControl("ImageUrlLabel")).Text;
        string ProductID = ((HiddenField)DataList1.Controls[0].FindControl("HiddenField1")).ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["techdata"].ToString());


我认为您在写这篇文章很有趣,因为它不仅是写得不好,但这绝对是不安全的.您不应该先购买一些书籍并阅读它们,然后再深入研究一个有趣的学习型项目.
I assume you''re writing this for fun, because not only is it badly written, but it''s definitely very insecure. You shouldn''t dive this deep into a fun, learning type project, without first buying some books and reading them.


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

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