Rajneesh Dhariwal
Rajneesh Dhariwal

Reputation: 39

Events not Working

My custom Class events not working. Here is my code:

public delegate void ChangedEventHandler(object sender, EventArgs e, int p);

When I am not using delegate { }, I am getting error:

Object reference not set to an instance of an Object.

public event EventHandler DownloadCompleted = delegate { };
public event ChangedEventHandler DownloadProgressChanged = delegate { };

public void DownloadFile(String url, String localFilename)
{

    try
    {
        Application.DoEvents();
        WebRequest req = WebRequest.Create(url);
        WebResponse response = req.GetResponse();
        Stream stream = response.GetResponseStream();
        byte[] downloadedData = new byte[0];

        int downloaded = 0;

        byte[] buffer = new byte[1024];
        int totalData = (int)response.ContentLength;
        int a = 0;

        FileStream file = File.Create(localFilename);

        while (true)
        {

            if (paused == false)
            {
                Application.DoEvents();
                int bytesRead = stream.Read(buffer, 0, buffer.Length);

                if (bytesRead == 0)
                {
                    file.Flush();
                    file.Close();
                    DownloadCompleted(this, new EventArgs());
                    break;
                }
                file.Write(buffer, 0, bytesRead);

                downloaded += bytesRead;
                DownloadProgressChanged(this, EventArgs.Empty, downloaded);
            }
        }
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }

}

using in other class like this:

Downloader dw = new Downloader();
dw.DownloadFile(txt_url.Text, txt_path.Text);
dw.DownloadCompleted += dw_DownloadCompleted;
dw.Changed +=dw_Changed;

void wb_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    MessageBox.Show("Completed!");
}

void wb_DownloadProgressChanged(object sender,DownloadProgressChangedEventArgs e)
{
    //Setting ProgressBar Value
    progressBar1.Maximum = 100;
    progressBar1.Value = e.ProgressPercentage;
}

But ProgressBar not working.

What's wrong in my code?

Upvotes: 1

Views: 125

Answers (1)

Andrey Korneyev
Andrey Korneyev

Reputation: 26836

You have to assign event handlers in your "other" class before calling DownloadFile:

Downloader dw = new Downloader();
dw.DownloadCompleted += dw_DownloadCompleted;
dw.Changed +=dw_Changed;
dw.DownloadFile(txt_url.Text, txt_path.Text);

You also don't need to assign empty event handlers like = delegate { }.

Otherwise at the time when DownloadFile tries to call DownloadCompleted and Changed event handlers - they are null references, that's why you're getting that error. Assigning empty event handlers prevents NullReferenceException, but since you're assigning empty event handlers to your events - they obviously do nothing.

Upvotes: 3

Related Questions