1
votes

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?

4
Check the that doc.Element("stock") actually has a value and is not returning null. - Justin Harvey
ok i will check whether the doc is null or not thankyou. I will intimidate you wait - Mr_Green
I think the doc is not null. I edited my question - Mr_Green
Almost all cases of NullReferenceException are the same. Please see "What is a NullReferenceException in .NET?" for some hints. - John Saunders

4 Answers

1
votes

You are getting the exception because:

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

stock is the root node, and doc.Element("stock") returns null. What you are actually trying to do is to add an item in your xml. Try the following:

doc.Add(newElement);

This will give you the desired result.

1
votes

eather doc.Element("stock") can't be found and is NULL or doc is NULL

1
votes

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;" at the top of the file.

1
votes

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.

Try adding this

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

before

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