我的LINQ to XML代码中的空引用异常 [英] Null reference exception in my LINQ to XML code

查看:70
本文介绍了我的LINQ to XML代码中的空引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将XML文件链接到下拉列表和gridviews.

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

我设法从XML文档中填充了一个下拉列表,然后将GridView填充到了另一个列表中,但是当尝试添加where子句时,我得到了一个空引用异常,并且不确定为什么.我该如何解决?

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();

推荐答案

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

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"),
        };

这篇关于我的LINQ to XML代码中的空引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆