我的 LINQ to XML 代码中出现空引用异常
我一直在尝试将 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();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
避免使用
.Value
;可以使用一系列空安全隐式转换运算符:Avoid using
.Value
; a range of null-safe implicit conversion operators are available:其中任何一个:
都可以为 null,然后对它们调用 .ToString() 或 .Value 会给您带来您所看到的异常。
如果您不乐意通过 NullReferenceExceptions 捕获 XML 问题,那么您需要将 Attribute() 调用的值放入局部变量中,然后对其进行测试(或者调用它两次并测试第一次调用是否为 null)。
Any of these:
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).
尝试:
其中 c.Attribute("PropertyId") != null &&条件部分的 c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString()
和c.Element("ThumbUrl") != null
。您的代码应如下所示:Try:
where c.Attribute("PropertyId") != null && c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString()
for the condition part andc.Element("ThumbUrl") != null
. Your code should look like this: