繁体   English   中英

Linq中的空引用异常

[英]Null reference exception in Linq

我是.net初学者。 在问这里之前我经历了很多网站。 我收到错误 - “对象引用未设置为对象的实例。” 。这个错误通常出现在任何控件中都有空值但在我的情况下每个控件都有一些文本,那么为什么会出现这个错误呢? 这是我的xml文件

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

我尝试了下面的代码:

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

编辑:

而不是使用

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

我用了

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

问题解决了。 为什么这样?

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

鉴于代码有限,不容易看到您添加和/或断言存在的内容。 尝试在错误之上添加这两行,错误消息将指示错误。

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!");

您可能需要包含“使用System.Diagnostics;” 在文件的顶部。

我猜你没有用现有的XML预加载doc ,如果是这样的话,就不会有任何stock元素。

尝试添加此功能

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

之前

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

你得到了例外,因为:

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

stock是根节点, doc.Element("stock")返回null。 你实际上要做的是在你的xml中添加一个项目。 请尝试以下方法:

doc.Add(newElement);

这将为您提供所需的结果。

暂无
暂无

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

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