2011-12-15 10 views
0

オンラインで豊富な情報を見てきましたが、これを修正するための何かが見つかりませんでした。私はこれにはとても新しいので、これはあなたのためにとても基本的な場合は謝罪します。あなたは私が学ぶのを手伝っています:)NullReferenceExceptionが処理されていません

アプリケーションはうまくいきますが、ユーザーがリストボックスから何も選択せず、代わりに「Do We Match」ボタンを押すとプログラムがクラッシュします。私はそれが彼らが各リストのstarsignをクリックすることを要求するエラーを投げるために必要です(公式のエラーは 'Null参照例外は未処理です)。これまでにその部分について

コード:

私はあなたに感謝し、誰かが役立つことを願って
 // Method for starsign combinations 
    public void Combinations() 
    { 

     ListBoxItem lbi = (ListBoxItem)yourListBox.SelectedItem; 
     string yourListBoxValue = (string)lbi.Content; 

     ListBoxItem lbi2 = (ListBoxItem)partnerListBox.SelectedItem; 
     string partnerListBoxValue = (string)lbi2.Content; 



     string listBoxValuesCombined = yourListBoxValue + partnerListBoxValue; 

     if ((listBoxValuesCombined == "Aries" + "Aries") || (listBoxValuesCombined == "Aries" + "Aries")) 
      resultTextBlock.Text = "On Fire - this is a hot combination!"; 

答えて

0

各ListBoxItemのContentプロパティにアクセスする前に、ListBoxのSelectedItemプロパティを確認してください。あなたの組み合わせ方法の先頭にnullをこのチェックを入れ、続行する前に、両方のリストボックスに値を持つようにしたいので、:

public void Combinations() 
{ 
    if (yourListBox.SelectedItem == null || partnerListBox.SelectedItem == null) 
    { 
    resultTextBlock.Text = "Please select a sign for yourself and your partner."; 
    return; 
    } 

リストボックスで選択した値がない場合には、SelectedItemプロパティはnullになります。したがって、上記のListBoxItemを取得した場合:

ListBoxItem lbi = (ListBoxItem)yourListBox.SelectedItem; 

lbiは値nullで終わります。 lbi.Contentを取得しようとすると、NullReferenceExceptionがスローされます。 lbiはnullなので、Contentプロパティを取得するオブジェクトはありません。

+0

ありがとう、魅力のように動作します! :D – AppGirl

0
public void Combinations() 
{ 
    if ((ListBoxItem)yourListBox.SelectedItem == null 
     || (ListBoxItem)partnerListBox.SelectedItem == null) return; 

    ListBoxItem lbi = (ListBoxItem)yourListBox.SelectedItem; 
    string yourListBoxValue = (string)lbi.Content; 

    ListBoxItem lbi2 = (ListBoxItem)partnerListBox.SelectedItem; 
    string partnerListBoxValue = (string)lbi2.Content; 



    string listBoxValuesCombined = yourListBoxValue + partnerListBoxValue; 

    if ((listBoxValuesCombined == "Aries" + "Aries") || (listBoxValuesCombined == "Aries" + "Aries")) 
     resultTextBlock.Text = "On Fire - this is a hot combination!"; 
+0

ありがとう、よろしく! :D – AppGirl

関連する問題