简体   繁体   中英

Null reference exception in my LINQ to XML code

I have been playing around with linking XML files to dropdown lists and gridviews.

I have managed to populate one dropdown list from the XML document and then a gridview to another but when try to add a where clause, I get a null reference exception and not sure why. How can I resolve this?

XDocument xmlDoc = XDocument.Load(Server.MapPath("XMLFile.xml"));
var q = from c in xmlDoc.Descendants("Images")
        where c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString()
        select new
        {
            PropertyID = c.Element("ThumbUrl").Value,
        };
GridView1.DataSource = q;
GridView1.DataBind();

Avoid using .Value ; a range of null-safe implicit conversion operators are available:

var q = from c in xmlDoc.Descendants("Images")
        where (string)c.Attribute("PropertyId")
               == DropDownList1.SelectedValue.ToString()
        select new
        {
            PropertyID = (string)c.Element("ThumbUrl"),
        };

Any of these:

c.Attribute("PropertyId")
c.Element("ThumbUrl")
DropDownList1.SelectedValue

could be null, and then calling .ToString() or .Value on them would give you the exception you're seeing.

If you're not happy to catch XML problems via NullReferenceExceptions, then you need to take the value of the Attribute() call into a local variable and then test against that (or call it twice and test the first call for null).

from x in document.Descendants("Images")
let xElement = x.Element("PropertyId")
where xElement != null && xElement.Value == DropDownList1.SelectedValue.ToString()
select new
{
   PropertyID = c.Element("ThumbUrl").Value,
};

Try: where c.Attribute("PropertyId") != null && c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString() for the condition part and c.Element("ThumbUrl") != null . Your code should look like this:

XDocument xmlDoc = XDocument.Load(Server.MapPath("XMLFile.xml"));
var q = from c in xmlDoc.Descendants("Images")
        where c.Attribute("PropertyId") != null 
        && c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString() 
        && c.Element("ThumbUrl") != null
        select new
        {
            PropertyID = c.Element("ThumbUrl").Value,
        };
GridView1.DataSource = q;
GridView1.DataBind();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM