[英]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.