Click here to Skip to main content
15,886,067 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Am trying to loop through xmlnodes. but getting this error "Object reference not set to an instance of an object." My main goal was to loop it through the datgridviewcell but i don't know how i can take it further. I know the column indexes for font,date and comment from my grid. how can i loop through those column indexes and be able to parse the value to string?

My code
<root> <value> <comment>[Font]Bold[/Font][DateStamp][/DateStamp][Comment][/Comment]


Font is index 2 from my datagridview
DateStamp is index 3 from my datagridview
Comment is index 4 from my datagridview
C#
XmlNodeList _Nodelist = _doc.SelectNodes("/root");
               foreach(XmlNode _Xnode in _Nodelist)
               {
                   XmlNode _data = _Xnode.SelectSingleNode("data");
                   XmlNodeList _CommentNodes = _data.SelectNodes("comment");
                   if(_CommentNodes != null)
                   {
                       foreach(XmlNode node in _CommentNodes)
                       {
                           XmlNode _comment = node.SelectSingleNode("comment");
                           {

                                   string _font = _comment["Font"].InnerText; //it throws the error here
                                   string _Date = _comment["DateStamp"].InnerText;
                                   string _Comment = _comment["Comment"].InnerText;
                           }
                       }
                   }
               }
Posted
Updated 24-Feb-15 23:50pm
v3

This error is because of _comment["Font"] is null.

Check _comment["Font"] is not null.
Put if condition here like below

if(null!=_comment["Font"])
{
string _font = _comment["Font"].InnerText;
}


It will work for sure. :)
 
Share this answer
 
Comments
[no name] 25-Feb-15 10:05am    
It will work for sure? I would like to see your face when the following two lines cause the whole thing to fall flat on its face again after your 'working for sure' correction.
Bacanzela 26-Feb-15 7:59am    
Thanks!
If your comment is correct, then _comment["Font"] in that line must be null. Trying to access the InnerText property leads to the exception.

There are unneeded brackets after this line:
XmlNode _comment = node.SelectSingleNode("comment");

Could those brackets belong to a if(_comment != null), which somehow got lost?

Also, you will have to individually test wether or not _comment["Font"], _comment["DateStamp"] or _comment["Comment"] really exist (are not null) before accessing any of their properties.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900