Reputation: 1
I have my resources embedded in the system, the string I search for them with matches the name of the image yet I still get a ArgumentNullException... How come?
//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;
}
Thank you so much in advance!
Upvotes: 0
Views: 58
Reputation: 52290
You've got a small logic flaw. You are setting variables inside an if
condition but using them outside, even if the if
condition doesn't execute.
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;
You should probably change it to something more like this:
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; }
}
Or better yet, use a guard, and use local variables, so that the compiler will catch this sort of flaw in the 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;
Upvotes: 1