0

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?

svick
  • 236,525
  • 50
  • 385
  • 514
Daniel B
  • 8,770
  • 5
  • 43
  • 76
  • 1
    Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Nov 16 '13 at 22:40
  • @JohnSaunders Thank you for that link! That will come in useful in the future, I'm sure! – Daniel B Nov 16 '13 at 22:40

1 Answers1

4

You forgot to initialize your components in your second constructor. So the Nullpointer isn't called because there is no picture, but because the pictureBox isn't initialized

public TestImageForm(Image img)
{
    InitializeComponent();
    bevImg = img;
    displayImage();
}
Daniel Abou Chleih
  • 2,440
  • 2
  • 19
  • 31
  • Thank you, Daniel A.C! This really shows me that the risks of sloppy mistakes always are present, and that I perhaps shouldn't code when I am tired. Many thanks for saving me from more unnecessary debugging! – Daniel B Nov 16 '13 at 22:42
  • You're welcome. Sometimes you just overlook the most obvious mistakes (especially when you're tired). Better get some sleep now :P – Daniel Abou Chleih Nov 16 '13 at 22:45