gpt4 book ai didi

c# - Linq 中的空引用异常

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:40 24 4
gpt4 key购买 nike

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

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

我尝试了下面的代码:

点击按钮

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

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

最佳答案

您得到异常是因为:

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

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

doc.Add(newElement);

这会给你想要的结果。

关于c# - Linq 中的空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12795803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com