我的LINQ to XML代码中的空引用异常

Kev*_*Kev 1 c# xml linq linq-to-xml nullreferenceexception

我一直在努力将XML文件链接到下拉列表和网格视图.

我已经设法从XML文档填充一个下拉列表,然后将gridview填充到另一个,但是当尝试添加where子句时,我得到一个空引用异常并且不确定原因.我该如何解决这个问题?

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();
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

避免使用.Value; 一系列零安全隐式转换运算符可用:

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