2011-04-22 3 views
1

XML 파일을 드롭 다운 목록 및 gridview에 연결하여 사용하고 있습니다.LINQ to XML 코드의 Null 참조 예외

XML 문서에서 하나의 드롭 다운 목록을 채운 다음 gridview를 다른 곳으로 채우지 만 where 절을 추가하려고하면 null 참조 예외가 발생하고 그 이유는 확실하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?

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

는 nullreference는 던져'where' 부분? "이미지"노드에 "PropertyId"속성이 있습니까? –

+0

괜찮 았어 덕분에 그 점에 대해 많은 감사를드립니다. 마지막 질문 하나를 도울 수 있다면 .... hte gridview는 이제 드롭 다운 상자가 변경 될 때 정확한 ThumbUrl을 보여줍니다.하지만 어떻게 링크 뷰를 변경해야합니까? 그냥 URL을 보여주는 것과 반대되는 이미지? – Kev

+0

Kev - StackOverflow를 최대한 활용하려면 투표하는 데 도움이되는 답변을 받아야합니다. 두 번째 질문에 대한 답변을 얻는 기회가 훨씬 많습니다. 논평. –

답변

0

시도 : 조건 부분에 대한 where c.Attribute("PropertyId") != null && c.Attribute("PropertyId").Value == DropDownList1.SelectedValue.ToString()c.Element("ThumbUrl") != null. 코드는 다음과 같아야합니다

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

다음 중 하나 :

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

null이 될 수 있으며, 다음로 .toString()를 호출하거나 그들에 .Value는 당신에게 당신이보고있는 예외를 줄 것이다 .

NullReferenceExceptions을 통해 XML 문제를 파악하는 것이 어렵다면 Attribute() 호출의 값을 로컬 변수로 가져 와서 테스트하거나 (또는 ​​두 번 호출하여 첫 ​​번째 호출을 테스트해야합니다. 없는).

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

이것은 더 많은 인정을받을 자격이 있습니다 – Marcus

+0

오늘을 구했습니다! – Skinner927

0
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, 
};