0

I'm trying to fill my ProgressBar inside a while loop. But somehow the Progressbar value wont grow.

I want the code to open a textfile and to post a request for each row in it.

My code for this:

public void registerAccounts()
{
    const Int32 BufferSize = 128;
    using (var fileStream = File.OpenRead(nsTextBox3.Text))
    using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true, BufferSize))
    {
        String line;
        while ((line = streamReader.ReadLine()) != null)
        {
            var request = (HttpWebRequest)WebRequest.Create("http://registration.zwinky.com/registration/register.jhtml");
            var postData = "form=reg&success=http://profile.zwinky.com/zwinkyprofile/main.jhtml?username=&tp=&user.partnerId=ZZzer000&source=zwinky&design=classic&ad=/&user.userName=" + line + "&user.password=" + nsTextBox1.Text + "&user.passwordConfirm=" + nsTextBox1.Text + "&user.secretQId=1&user.secretQAnswer=" + line + "&user.birthdayMonth=1&user.birthdayDay=1&user.birthdayYear=1996&user.gender=M&user.emailAddr=" + nsTextBox2.Text + "&emailAddrConfirm=" + nsTextBox2.Text + "&x=42&y=51&partnerCode=/";
            var data = Encoding.ASCII.GetBytes(postData);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = data.Length;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(data, 0, data.Length);
            }
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }
    }
}

How would I let the ProgressBar in my GUI grow now?

I thought about counting the lines inside the text document like this:

var lineCount = File.ReadLines(nsTextBox3.Text).Count();

and then run a for loop in it. But it wont grow sadly.

Would appreciate any kind of help.

d4n3x
  • 1
  • 1
  • 1
  • 6
    possible duplicate of [Update progress bar from for loop](http://stackoverflow.com/questions/12617826/update-progress-bar-from-for-loop) – Flynn1179 Aug 28 '15 at 10:27
  • 1
    Or http://stackoverflow.com/questions/1194620/how-do-i-display-progress-during-a-busy-loop, http://stackoverflow.com/questions/3727191/how-do-i-update-the-progress-bar-one-step-every-loop-cycle-c-sharp – Flynn1179 Aug 28 '15 at 10:29

2 Answers2

2

You appear to be running this method on the UI thread of your application. This thread is responsible for updating the UI, so while it's busy with the loop it can't do that. What likely happens is that once your loop completes the progress bar is updated straight to 100% and you don't see it.

Look at using a Background Worker.

It takes care of the above concerns by doing all of the threading and callbacks for you in a very simple manner.

Example taken straight from the MSDN article:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SL_BackgroundWorker_CS
{
    public partial class Page : UserControl
    {
        private BackgroundWorker bw = new BackgroundWorker();

        public Page()
        {
            InitializeComponent();

            bw.WorkerReportsProgress = true;
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
        }
        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            if (bw.WorkerSupportsCancellation == true)
            {
                bw.CancelAsync();
            }
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; (i <= 10); i++)
            {
                if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress((i * 10));
                }
            }
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if ((e.Cancelled == true))
            {
                this.tbProgress.Text = "Canceled!";
            }

            else if (!(e.Error == null))
            {
                this.tbProgress.Text = ("Error: " + e.Error.Message);
            }

            else
            {
                this.tbProgress.Text = "Done!";
            }
        }
        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
        }
    }
}

Put your loop in DoWork and your progress bar in ProgressChanged. Simples!

Equalsk
  • 7,954
  • 2
  • 41
  • 67
0

you can try this,this is not perfect but worked

int linecount=0;

while ((line = streamReader.ReadLine()) != null)
{
linecount=linecount+1;
}

int number=0;

while ((line = streamReader.ReadLine()) != null)
 {
number=number+1;

    // what is yor work

progressBar1.Value = i * progressBar1.Maximum / linecount;  //show process bar counts
LabelTotal.Text = i.ToString() + " of " + linecount; //show number of count in lable
int presentage = (i * 100) / linecount;
LabelPresentage.Text = presentage.ToString() + " %"; //show precentage in lable
Application.DoEvents(); //keep form active in every loop 
}