Reputation: 23
Good morning.
Shortly.
Using XmlDocument I'm programmaticaly creating document, which needs to look like this (sample):
<report>
<header version="1" reportDate="2013-08-27" salesDate="2013-08-26"/>
<data>
<companies>
<company id="ABCD">
<customers>
<customer id="100000" storeId="AA"/>
<customer id="100001" storeId="AB"/>
<customer id="100002" storeId="AC"/>
</customers>
</company>
</companies>
</data>
</report>
I need to grab the data from a few DataGridView's so the foreach loops are intensively in use.
Which I can't work out nor to find the answer (always something about reading the XML, no creating) is why the code shown below throws me:
Object reference not set to an instance of an object
This is a sample of code I use:
[...]
XmlNode customersNode = doc.CreateElement("customers");
companyNode.AppendChild(customersNode);
XmlNode customerNode;
XmlAttribute customerAttribute;
foreach (DataGridViewRow row in dgvCustomers.Rows)
{
customerNode = doc.CreateElement("customer");
customerAttribute = doc.CreateAttribute("id");
customerAttribute.Value = row.Cells[0].Value.ToString();
//
// __HERE__ is the problem (or a line above)
//
customerNode.Attributes.Append(customerAttribute);
customerAttribute = doc.CreateAttribute("storeId");
customerAttribute.Value = row.Cells[1].Value.ToString();
customerNode.Attributes.Append(customerAttribute);
customersNode.AppendChild(customerNode);
}
[...and so on...]
Also
customerNode.Attributes.Append(customerAttribute);
underlined (VS2010 editor) with this tip:
Possible 'System.NullReferenceException'
but I assume this is a reason of the problem described above?
Any support is appreciated and many thanks in advance for your time and knowledge share.
Best regards!
Upvotes: 1
Views: 783
Reputation: 1062502
I haven't tried running the code shown, but : you might find that simplifying it makes it harder to get wrong:
XmlElement customerNode; // <==== note this is XmlElement, not XmlNode
XmlAttribute customerAttribute;
foreach (DataGridViewRow row in dgvCustomers.Rows)
{
customerNode = doc.CreateElement("customer");
customerNode.SetAttribute("id", row.Cells[0].Value.ToString());
customerNode.SetAttribute("storeId", row.Cells[1].Value.ToString());
customersNode.AppendChild(customerNode);
}
You might also want to check that the issue isn't actually that row.Cells[0].Value.ToString()
or row.Cells[1].Value.ToString()
is throwing an exception.
Upvotes: 1