I am .net beginner. 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
cmbProduct --> combobox
txtNewBrand --> textBox
txtUpdateQuantity --> textBox
txtUpdatePrice --> textBox
I tried the below code:
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?
You are getting the exception because:
stockis the root node, anddoc.Element("stock")returns null. What you are actually trying to do is to add an item in your xml. Try the following:This will give you the desired result.