Click here to Skip to main content
15,942,761 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am developing a Download manager. And I want to implement progress bar, but it is not working(not Updating value) What can I do?
Please go through my code.
Thanks in Advance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
using System.Windows.Controls.Primitives;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Windows;
using System.Net;
using System.Threading;
using System.Reflection;

namespace DownloadManager
    /// <summary>
    /// Interaction logic for Download.xaml
    /// </summary>
    public partial class Download : Window
        public Download()
           this.Loaded += OnLoad;


     Uri uri;

       static int row = 0;

        private void Button_Click(object sender, RoutedEventArgs e)

        private volatile bool _allowedToRun;
        private string _source;
        private string _destination;
        private int _chunkSize;
        Download d1 ;

        private Lazy<int> _contentLength;

        public int BytesWritten { get; private set; }
        public int ContentLength { get { return _contentLength.Value; } }

        public bool Done { get { return ContentLength == BytesWritten; } }

        public Download(string source, string destination, int chunkSize)
            _allowedToRun = true;

            _source = source;
            _destination = destination;
            _chunkSize = chunkSize;
            _contentLength = new Lazy<int>(() => Convert.ToInt32(GetContentLength()));

            BytesWritten = 0;
        private long GetContentLength()
            var request = (HttpWebRequest)WebRequest.Create(_source);
            request.Method = "HEAD";

            using (var response = request.GetResponse())
                return response.ContentLength;
        public event PropertyChangedEventHandler PropertyChanged;

        private int _Progress;
        public int Progress
                return _Progress;

                _Progress = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Progress"));
     static public int p;
        private async Task Start( int range)
            if (!_allowedToRun)
                throw new InvalidOperationException();

            var request = (HttpWebRequest)WebRequest.Create(_source);
            request.Method = "GET";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            using (var response = await request.GetResponseAsync())
                using (var responseStream = response.GetResponseStream())
                    using (var fs = new FileStream(_destination, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                        while (_allowedToRun)
                            var buffer = new byte[_chunkSize];
                            var bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length);

                            if (bytesRead == 0) break;

                            await fs.WriteAsync(buffer, 0, bytesRead);
                            BytesWritten += bytesRead;
                            double receive = double.Parse(BytesWritten.ToString());

                            double Filesize = 5761048;
                            double Percentage = receive / Filesize * 100;

                            // a1 = int.Parse(Math.Truncate(Percentage).ToString());
                            //pb.Value = int.Parse(Math.Truncate(Percentage).ToString());
                            // MessageBox.Show(int.Parse(Math.Truncate(Percentage).ToString()) + "Done");
                            int per = int.Parse(Math.Truncate(Percentage).ToString());
                            p = per;
                            // change(p);
                          //  MakeButton2();
                        await fs.FlushAsync();

        public Task Start()
            _allowedToRun = true;
            return Start( BytesWritten);
        public void Pause1()
            _allowedToRun = false;

        void MakeButton2()
            Button b2 = new Button();
            //  b2.AddHandler(Button.ClickEvent, new RoutedEventHandler(Onb2Click2));
            // MessageBox.Show("HI");
         b2.Click += new RoutedEventHandler(Onb2Click2);
           // b2.AddHandler(Button.ClickEvent, new RoutedEventHandler(Onb2Click2));
           // Onb2Click2(null, RoutedEventArgs.Empty);
           // Onb2Click2(this, new RoutedEventArgs());

           //Onb2Click2(new object(), new RoutedEventArgs());

       public void Onb2Click2(object sender, RoutedEventArgs e)
           //    Button b = b2(sender);
           // MessageBox.Show("Hi");
          // ProgressBar pb= e.Source as ProgressBar;
            pb.Value = p;

            MessageBox.Show(p + "");
        void OnLoad(object sender, RoutedEventArgs e)
          //  pb.Value = p;
            MessageBox.Show(p + "");


        public void change (  int i)
                MessageBox.Show(i + "");
           // pb.Value = i;

        private void Pause_Click(object sender, RoutedEventArgs e)
            //pb.Value = p;

               Onb2Click2(sender, e);
            catch (Exception ex) { MessageBox.Show(ex.Message); }



What I have tried:

I have tried to direct update the value but it is throwing exception :-
object reference not set to an instance
Updated 28-Jan-22 21:09pm

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, it will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debugger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
Share this answer
Nehal Chaudhari 29-Jan-22 3:28am    
Thank You sir, Any Solution??
OriginalGriff 29-Jan-22 3:39am    
Did you read what I said, at all?
Nehal Chaudhari 29-Jan-22 3:42am    
Yes sir, I am asking about other solutions to update progress bar value

I think the issue is with object sender
I am trying to change the value of my progressbar value and in change method i dont have object paramenter.

My WPF ProgressBar is defined as follows:
<progressbar margin="25,385,0,0" name="PBar" horizontalalignment="Left" verticalalignment="Top" width="554" height="30" value="0">

and within a loop, updates with:
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900