2017-10-11 141 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,并使用局部变量,这样编译器将捕捉这种缺陷在未来:

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; 
相关问题