Fairly new to coding, not sure where I've gone wrong here. The application Builds but crashes at runtime with the error: "Object reference not set to an instance of an object."
If I comment out test2 variable and 2nd condition then the application does what I want. When I un-comment the aforementioned then I get an exception.
I will eventually need to build something similar for a form of 30 checkboxes.
Any help would be greatly appreciated.
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"\\LEWBWPDEV\\ComplianceXmlStorage\\test.xml");
string test1 = xDoc.SelectSingleNode("Introduction/Topic1").InnerText;
string test2 = xDoc.SelectSingleNode("Introduction/Topic2").InnerText;
if (test1 == "Yes")
{
checkBox1.CheckState = CheckState.Checked;
}
if (test2 == "Yes")
{
checkBox2.CheckState = CheckState.Checked;
}
It means that you don't have Topic2
in your xml. So xDoc.SelectSingleNode("Introduction/Topic2")
returns null
. When you try to get InnerText
of null
you get an exception.
Solution - check for null before getting InnerText
.
var topic2 = xDoc.SelectSingleNode("Introduction/Topic2");
if (topic2 != null && topic2.InnerText == "Yes")
checkBox2.CheckState = CheckState.Checked;
Or you can use Null-conditional operator
string test2 = xDoc.SelectSingleNode("Introduction/Topic2")?.InnerText;
NOTE: I suggest you to use Linq to XML for parsing xml
var xdoc = XDocument.Load(fileName);
string test1 = (string)xdoc.XPathSelectElement("Introduction/Topic1");
string test2 = (string)xdoc.Root.Element("Topic2");
You can cast elements to some datatypes (like string or int) and it will not throw exception if element is missing (if data type accept null values). Also if you need to process 30 nodes, you can easily get all their values:
var topics = from t in xdoc.Root.Elements()
let name = t.Name.LocalName
where name.StartsWith("Topic")
select new {
Name = name,
IsEnabled = (string)t == "Yes"
};
This query will return collection of all topics values from your xml which you can use to set states of checkboxes
[
{ Name: "Topic1", IsEnabled: false },
{ Name: "Topic2", IsEnabled: true }
]