2017-10-11 5 views
0

私のリソースがシステムに埋め込まれていますが、それらを検索する文字列が画像の名前と一致していますが、引き続きArgumentNullExceptionが発生します。リソースから画像をロードしようとしたときにNullExceptionErrorが発生しました

//Check if currencies are chosen 
    private void Action() 
    { 
     label1.Text = null; 
     //Checks if items are selected then what currencies are chosen 
     if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1) 
     { 
      label1.Text = "Please select currencies"; 
     } 
     else 
     { 
     LB1 = listBox1.SelectedItem.ToString(); 
     LB2 = listBox2.SelectedItem.ToString(); 
     Conversion(); 
     } 
     pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image; 
     pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image; 
    } 
Picture of Resource images

は、事前にどうもありがとうございます!

+0

'SelectedItem.ToString()'は期待していた結果を返しますか?私はあなたがおそらく代わりに 'SelectedValue'を望んでいると思います。 –

+0

ToStringメソッドは正常に動作しているようですが、テストして正しい値を返すので、AUDを押して文字列AUDを返します。本当に奇妙なエラーです –

答えて

1

あなたは小さな論理欠陥があります。 ifの条件が実行されない場合でも、変数はifの中に設定していますが、それらを外部で使用しています。

if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1) 
{ 
    label1.Text = "Please select currencies"; 
} 
else 
{ 
    LB1 = listBox1.SelectedItem.ToString(); //Doesn't always run 
    LB2 = listBox2.SelectedItem.ToString(); 
    Conversion(); 
} 
//Always runs 
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image; 
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image; 

あなたは、おそらくより多くのこのような何かにそれを変更する必要があります。

if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1) 
{ 
    label1.Text = "Please select currencies"; 
} 
else 
{ 
    LB1 = listBox1.SelectedItem.ToString(); 
    LB2 = listBox2.SelectedItem.ToString(); 
    Conversion(); 
    pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(LB1) as Image; 
    pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(LB2) as Image;  } 
} 

いっそ、guardを使用し、コンパイラができずのこの種をキャッチするように、ローカル変数を使用future:

if (listBox1.SelectedIndex == -1 || listBox2.SelectedIndex == -1) 
{ 
    label1.Text = "Please select currencies"; 
    return; 
} 
var lb1 = listBox1.SelectedItem.ToString(); 
var lb2 = listBox2.SelectedItem.ToString(); 
Conversion(lb1, lb2); 
pictureBox1.Image = Properties.Resources.ResourceManager.GetObject(lb2) as Image; 
pictureBox2.Image = Properties.Resources.ResourceManager.GetObject(lb2) as Image; 
関連する問題