I have an async
method that downloads an image from a URL and then creates a new form in which the image should be displayed inside a PictureBox
.
This is how I download the image:
private void downloadImage(string url)
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(url, UriKind.Absolute));
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
Bitmap bmi = new Bitmap(e.Result);
bevImg = bmi;
Console.WriteLine("Image dimensions: " + bevImg.Size);
TestImageForm tif = new TestImageForm(bevImg);
tif.Show();
}
This is the class in which the image is to be displayed, and where the NRE is thrown:
public partial class TestImageForm : Form
{
Image bevImg;
public TestImageForm()
{
InitializeComponent();
}
public TestImageForm(Image img)
{
bevImg = img;
displayImage();
}
private void displayImage()
{
if (bevImg != null)
this.pictureBox1.Image = bevImg;
}
}
I get the NRE on the line that calls the set property of the picture box;
this.pictureBox1.Image = bevImg;
When I run the code, console prints out Image dimensions: {Width=180, Height=360}
, and that is correct when I compare it to the dimensions of the image I want to download.
I do not understand as to what it references in the NRE. The image clearly must be downloaded, otherwise the EventHandler wouldn't be called? Is it somehow referencing to my pictureBox, which has been added to the form in the designer?