2011-08-21 3 views
0

나는 결과가 null 인 경우 messagebox.show를 표시 할 수있는 다음을 가지고 있습니다. 하지만 여전히 처리되지 않은 예외를 제공합니다.Null을 재설정하는 방법은 무엇입니까? XML Linq

예외를 중지하고 사용자가 다른 값을 입력하도록하려면 어떻게합니까?

void Trademe_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
     { 
      if (e.Error != null) 
       return; 
      if (e.Error == null) 


       MessageBox.Show("Wrong try Again"); 

      var r = XDocument.Parse(e.Result); 
명확성을 위해

전체 코드 * ** * ** * ** * ** * ****

namespace TradeMe 
{ 
    public partial class MainPage : PhoneApplicationPage 
    { 
     // Constructor 
     public MainPage() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, RoutedEventArgs e) 
     { 
      WebClient Trademe = new WebClient(); 
      Trademe.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Trademe_DownloadStringCompleted); 
      Trademe.DownloadStringAsync(new Uri("http://api.trademe.co.nz/v1/Search/General.xml?search_string=" + TradeSearch.Text)); 

      progressBar1.IsIndeterminate = true; 
      progressBar1.Visibility = Visibility.Visible; 


     } 



     void Trademe_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
     { 
      if (e.Error != null) 
       return; 






      var r = XDocument.Parse(e.Result); 
      if (e.Result == null) 
       MessageBox.Show("Wrong try Again"); 


      // Declare the namespace 
      XNamespace ns = "http://api.trademe.co.nz/v1"; 
      listBox1.ItemsSource = from TM in r.Root.Descendants(ns + "Listing").Take(50) 
            select new TradeItem 
            { 
             ImageSource = TM.Element(ns + "PictureHref").Value, 
             Title = TM.Element(ns + "Title").Value, 
             Region = TM.Element(ns + "Region").Value, 
             PriceDisplay = TM.Element(ns + "PriceDisplay").Value, 
             ListingId = TM.Element(ns + "ListingId").Value, 
            }; 

      ; 

      progressBar1.IsIndeterminate = false; 
      progressBar1.Visibility = Visibility.Collapsed; 
     } 



     public class TradeItem 
     { 
      public string Region { get; set; } 
      public string ListingId { get; set; } 
      public string PriceDisplay { get; set; } 
      public string Title { get; set; } 
      public string ImageSource { get; set; } 
     } 

     private void hyperlinkButton1_Click(object sender, RoutedEventArgs e) 
     { 
      NavigationService.Navigate(new Uri("/TestPage.xaml", UriKind.Relative)); 
     } 

     private void eventhandler(object sender, SelectionChangedEventArgs e) 
     { 
      var item = (sender as ListBox).SelectedItem as TradeItem; 

      if (item != null) 
      { 
       string id = item.ListingId.ToString(); 
       NavigationService.Navigate(new Uri("/TestPage.xaml?ListingId=" + id, UriKind.Relative)); 
      } 


     } 


    } 
} 

전체 스택 추적 * ** * ** * ** * ****

at TradeMe.MainPage.<>c__DisplayClass2.<Trademe_DownloadStringCompleted>b__1(XElement TM) 
    at System.Linq.Enumerable.<SelectIterator>d__d`2.MoveNext() 
    at System.Windows.Controls.ItemCollection.EnumerableCollectionView.InitializeSnapshot() 
    at System.Windows.Controls.ItemCollection.EnumerableCollectionView..ctor(IEnumerable sourceCollection, ICollectionChangedListener collectionOwner) 
    at System.Windows.Controls.ItemCollection.UpdateItemsSourceList(IEnumerable newItemsSource) 
    at System.Windows.Controls.ItemsControl.ItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    at System.Windows.DependencyObject.RaisePropertyChangeNotifications(DependencyProperty dp, Object oldValue, Object newValue) 
    at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation) 
    at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value, Boolean allowReadOnlySet) 
    at System.Windows.DependencyObject.SetValueInternal(DependencyProperty dp, Object value) 
    at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value) 
    at System.Windows.Controls.ItemsControl.set_ItemsSource(IEnumerable value) 
    at TradeMe.MainPage.Trademe_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e) 
    at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e) 
    at System.Net.WebClient.DownloadStringOperationCompleted(Object arg) 
    at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark) 
    at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark) 
    at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters) 
    at System.Delegate.DynamicInvokeOne(Object[] args) 
    at System.MulticastDelegate.DynamicInvokeImpl(Object[] args) 
    at System.Delegate.DynamicInvoke(Object[] args) 
    at System.Windows.Threading.DispatcherOperation.Invoke() 
    at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority) 
    at System.Windows.Threading.Dispatcher.OnInvoke(Object context) 
    at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args) 
    at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args) 
    at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult) 

답변

1

당신은 e.Errore.Result가 null 여부, 널인지 확인하고 ... 그리고 당신은 또한을 보여주는 후 반환하지 않는 메세지 박스.

(그것은 일인지 정확히 알고 어렵다 - 당신은 당신이 어떤 상황에서 받고있는 무슨 예외 말할 수 있다면, 그 ... 유용 할 것이다)

편집 : 좋아, 스택 추적에서, iterator의 선택 부분에있는 것처럼 보입니다. 나는이 라인들 중 하나가 실패했다는 것을 강하게 의심한다 :

ImageSource = TM.Element(ns + "PictureHref").Value, 
Title = TM.Element(ns + "Title").Value, 
Region = TM.Element(ns + "Region").Value, 
PriceDisplay = TM.Element(ns + "PriceDisplay").Value, 
ListingId = TM.Element(ns + "ListingId").Value, 

내 생각 엔 당신이 찾고있는 요소 중 하나가 빠져있다.

다음 코드로 변경하면 예외가 발생하지 않지만 이전에 예외가 발생했던 속성은 null이됩니다. 그게 당신이 원하는 것을 할 수 있지만 적어도 잠재적으로 당신이 문제를 찾는 데 도움이 될 것입니다조차하지 않는 경우 : 요소가, 예를 들어, null의 경우

ImageSource = (string) TM.Element(ns + "PictureHref"), 
Title = (string) TM.Element(ns + "Title"), 
Region = (string) TM.Element(ns + "Region"), 
PriceDisplay = (string) TM.Element(ns + "PriceDisplay"), 
ListingId = (string) TM.Element(ns + "ListingId"), 

XElementstring에에서 명시 적 변환이 null를 돌려줍니다를 다음과 같이 .NET 4.0 MSDN 문서는 당신이 콜백을 처리해야 따라

XElement element = null; 
string value = (string) element; 
// value will be null; no exception is thrown 
+0

사용자가 검색을 위해 특정 값을 입력 할 때 처리되지 않은 예외 오류가 발생합니다. 전체 코드를 업데이트했습니다. 내가하고있는 일을 더 분명하게하기 위해서. – Rhys

+0

@Rhys : "처리되지 않은 예외 오류"는 여전히 정확하지 않습니다. 전체 스택 추적을 게시하고 관련 줄 번호를 레이블하십시오. 예를 들어, XML을 파싱하는 것을 관리하고 있지만 예상 한 요소가 포함되어 있지 않을 수 있습니다. –

+0

전체 스택 추적이 추가되었습니다. 감사합니다 – Rhys

0

:

private static void DownloadStringCallback2 (Object sender, DownloadStringCompletedEventArgs e) 
{ 
    // If the request was not canceled and did not throw 
    // an exception, display the resource. 
    if (!e.Cancelled && e.Error == null) 
    { 
     string textString = (string)e.Result; 

     Console.WriteLine (textString); 
    } 
} 

난 당신이 WP7 비슷한 뭔가를해야 가정. 따라서 Canceled가 false이고 e.Error가 null이 아닌지 확인하십시오. 그런 다음 결과를 얻으십시오.

관련 문제