简体   繁体   English

Linq中的空引用异常

[英]Null reference exception in Linq

I am .net beginner. 我是.net初学者。 I have gone through many sites before asking here. 在问这里之前我经历了很多网站。 I am getting error -- "Object reference not set to an instance of an object." 我收到错误 - “对象引用未设置为对象的实例。” .This error comes usually when there are null values in any control but in my case Every control has some text in them, then why this error coming? 。这个错误通常出现在任何控件中都有空值但在我的情况下每个控件都有一些文本,那么为什么会出现这个错误呢? here is my xml file 这是我的xml文件

cmbProduct        --> combobox 
txtNewBrand       --> textBox
txtUpdateQuantity --> textBox
txtUpdatePrice    --> textBox

I tried the below code: 我尝试了下面的代码:

onButtonClick onButtonClick

XElement doc = XElement.Load(@"..\..\stock.xml");
var newElement = new XElement("items",
                               new XElement("productname", cmbProduct.Text),
                               new XElement("brandname", txtNewBrand.Text),
                               new XElement("quantity", txtUpdateQuantity.Text),
                               new XElement("price", txtUpdatePrice.Text));
 /*ERROR*/      doc.Element("stock").Add(newElement);
                doc.Save(xpath);
                MessageBox.Show("updated successfully");

EDIT : 编辑:

Instead of using 而不是使用

XElement doc = XElement.Load(@"..\..\stock.xml");

i used 我用了

var doc = XDocument.Load(@"..\..\stock.xml");

and the problem solved. 问题解决了。 why so? 为什么这样?

无法找到eather doc.Element(“stock”)且为NULL或doc为NULL

Given the limited code it isn't easy to see what you have added and/or asserted to exist. 鉴于代码有限,不容易看到您添加和/或断言存在的内容。 Try adding these two lines above your error and the error message will indicate the fault. 尝试在错误之上添加这两行,错误消息将指示错误。

Debug.Assert(doc != null, "Can not operate without a valid instance of 'doc'");
Debug.Assert(doc.Element("stock") != null, "Need the stock element to add to!");

You may need to include "using System.Diagnostics;" 您可能需要包含“使用System.Diagnostics;” at the top of the file. 在文件的顶部。

I guess you didn't pre-load the doc with an existing XML, if so there won't be any stock element to start with. 我猜你没有用现有的XML预加载doc ,如果是这样的话,就不会有任何stock元素。

Try adding this 尝试添加此功能

if (doc.Element("stock") == null)
{
    doc.Add(new XElement("stock"));
}

before 之前

doc.Element("stock").Add(newElement);

You are getting the exception because: 你得到了例外,因为:

doc.Element("stock").Add(newElement);

stock is the root node, and doc.Element("stock") returns null. stock是根节点, doc.Element("stock")返回null。 What you are actually trying to do is to add an item in your xml. 你实际上要做的是在你的xml中添加一个项目。 Try the following: 请尝试以下方法:

doc.Add(newElement);

This will give you the desired result. 这将为您提供所需的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM