How to use progressbar.value property at different locations of program - c#

I need to use progressbar.value property at different locations. But the problem is, while executing it shows only maximum value given. I need to stop at 25% and 75% and after some delay, 100%. How can I overcome this problem. Thanks in Advance...
C#
namespace ProgressBarWindowForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, System.EventArgs e)
{
label1.Hide();
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 25;
if (progressBar1.Value == 25)
{
label1.Show();
label1.Text = "Process Complete 25%";
}
progressBar1.Value = 75;
if (progressBar1.Value == 75)
{
label1.Show();
label1.Text = "Process Complete 75%";
}
}
}
}
Progressbar control name is progressBar1,
Label name is label1 and
Button name is button1
When I Clicked the Button, progressbar value is directly filling with 75%. I want to stop it at 25% and after some delay it should fill 75% and then 100%...Can anyone help..Can I use "progressBar1.value" only Once or as many times I need?

try this,Drag and drop background worker in windows form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
private void button1_Click(object sender, EventArgs e)
{
// Start the background worker
backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
if (label1.InvokeRequired)
{
label1.Invoke(new MethodInvoker(delegate
{
label1.Show();
label1.Text = "Process Complete " + progressBar1.Value + "%";
}));
}
if (progressBar1.Value == 25 || progressBar1.Value == 75)
{
System.Threading.Thread.Sleep(1000);
}
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
}

Use a Timer to update the progress bar after a delay:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer.Tick += Timer_Tick;
timer.Interval = 1000; // delay: 1000 milliseconds
}
Timer timer = new Timer();
private void Timer_Tick(object sender, EventArgs e)
{
if (progressBar1.Value == 100)
{
timer.Stop();
return;
}
progressBar1.Value += 25;
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value = 25;
timer.Start();
}
}

Its simple to update progressBar values in button click, you can initialize the properties in the page load or else use the designer, in page load it would be like the following:
private int ProgressPercentage = 10;
public void Form1_Load(object sender, System.EventArgs e)
{
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
}
So the initialization completed, now you can code the button click like the following, through which you can update the progress bar in every button click:
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Value += ProgressPercentage;
label1.Text = String.Format("Process Complete {0}%",progressBar1.Value);
}
If you want the update to be happens automatically in a particular interval means you can make use of a timer and enable the timer in the button click. Here you can find a similar thread which can be used to implement timer to your scene.
Update as per your comment, calling a delay will not be a best practice, you can make use a timer here as like the following:
System.Windows.Forms.Timer proTimer = new System.Windows.Forms.Timer();
private void Form1_Load(object sender, EventArgs e)
{
proTimer.Interval = 1000;
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 0;
proTimer.Tick += new EventHandler(proTimer_Tick);
}
private void button1_Click(object sender, EventArgs e)
{
proTimer.Enabled = true;
proTimer.Start();
}
// Timer event
void proTimer_Tick(object sender, EventArgs e)
{
progressBar1.Value += ProgressPercentage;
label1.Text = String.Format("Process Complete {0}%",progressBar1.Value);
if (progressBar1.Value == 100)
{
proTimer.Stop();
proTimer.Enbled = false;
}
}

You need to add a delay inbetween the changes. As of now, the button advance the bar to 25, sets the label, then advances the bar to 75 without pausing.
System.Threading.Thread.Sleep(n); will sleep n milliseconds, which you will need after the statement setting the 25 percent marker.
EDIT
If you want it the value to only progress on a button click, you will need to check the value of the progress bar before you advance it.
In pseudo code, something like:
onclick() {
if (progress == 0) {
progress = 25
label = the25MarkText
} else if (progress == 25) {
progress = 75
label = the75MarkText
}
}

Related

How to use ProgressBar in C#?

I want to use the ProgressBar and run it from 100% to 0% within 2 seconds. I have written the following function but it does not seem to run properly. Please help! Thank you!
private async void progessbar()
{
for (iValue = 100; iValue >= 0; iValue--)
{
pbTime.Value = iValue;
await Task.Delay(20);
}
}
If you want to animate your progress bar smoothly, you should use a storyboard:
private void AnimateProgressBar()
{
var storyboard = new Storyboard();
var animation = new DoubleAnimation { Duration = TimeSpan.FromSeconds(2), From = 100, To = 0, EnableDependentAnimation = true };
Storyboard.SetTarget(animation, this.ProgressBar);
Storyboard.SetTargetProperty(animation, "Value");
storyboard.Children.Add(animation);
storyboard.Begin();
}
You are changing toolbar multiple times in the same Windows event. Windows updates GUI later when it is idle. Thus you probably see your toolbar jump from 0 to 100% after 2 second wait.
Just add timer to your control, set it when ready to start and do incremental updates.
// In your designer:
this.timer.Enabled = false;
this.timer.Interval = 200;
this.timer.Tick += new System.EventHandler(this.timer_Tick);
// when starting the progress:
pbTime.Value = 0
this.timer.Enabled = true;
private void timer_Tick(object sender, EventArgs e)
{
if (pbTime.Value < 100)
pbTime.Value += 10;
}
I hope this helps
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Start the BackgroundWorker.
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
/*Your main code*/
for (int i = 1; i <= 100; i++)
{
// Wait 20 milliseconds.
Thread.Sleep(20);
// Report progress.
backgroundWorker1.ReportProgress(i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
progressBar1.Value = e.ProgressPercentage;
// Set the text.
this.Text = e.ProgressPercentage.ToString();
}
}
}

Form timer doesn't start

So I just started learning C# and using forms. I have been able to create a digital clock and tinker with this and that, but now I'm trying to make a basic UI for a derpy game and my timer doesn't work.
First - what I'm trying to accomplish: A simple decrementing timer from 60 seconds (*clock style (mm:ss)).
Second, here's what I have:
public partial class Form1 : Form
{
private int counter = 60;
public Form1()
{
InitializeComponent();
label1.Text = TimeSpan.FromMinutes(1).ToString("m\\:ss");
}
private void pictureBox2_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
{
timer1.Stop();
label1.Text = counter.ToString();
MessageBox.Show("Time's Up!!");
}
}
private void label1_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
var counter = (TimeSpan.FromMinutes(1)).ToString("m\\:ss");
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
label1.Text = counter.ToString();
}
}
Appreciate the feedback and knowledge!
From the codes that I see, your timer is working but you are not updating it in each count, you are updating when the timer finishes -
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
{
timer1.Stop();
label1.Text = counter.ToString(); // *** Look here
MessageBox.Show("Time's Up!!");
}
}
You should update the timer in each tick, so take the update label code out of the if block -
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
label1.Text = counter.ToString(); // should work
if (counter == 0)
{
timer1.Stop();
MessageBox.Show("Time's Up!!");
}
}
and also reset the counter in each cycle -
private void label1_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
var counter = (TimeSpan.FromMinutes(1)).ToString("m\\:ss");
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
label1.Text = counter.ToString();
this.counter = 60
}
NOTE: I am really not sure if this code will throw any access
violation error, due to updating the UI in a different thread or not.
If so, then you have to use async/await or events/delegates to
update UI.
Let me know, if this throws error, then I will give you the async/await version.
This works fine for me. I would give progress updates as the time is countdown to show that it is working. For example, if you did this in label, you could do something like the following:
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
label1.Text = counter.ToString();
if (counter == 0)
{
timer1.Stop();
MessageBox.Show("Time's Up!!");
}
}
Notice that the label1.Text = counter.ToString(); line has been moved before the counter == 0 check, so that it is able to provide feedback for all counter values.
As well, you may accidentally launch several timer1 instances if you do not keep track of how many you spawn using new Timer(). There are various ways to do this, but you could simply check whether timer1 already exists and counter == 0 before creating a new instance. You could perform this check as a guard clause (ie. return if either of those conditions are matched).
private void label1_Click(object sender, EventArgs e)
{
var startTime = DateTime.Now;
if (timer1 == null || (timer1 != null && counter == 0)) return;
counter = (TimeSpan.FromMinutes(1)).ToString("m\\:ss");
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
label1.Text = counter.ToString();
}
If you want this countdown to start automatically, you can put this directly into the constructor, or put it into another method and call it from the constructor like so:
public Form1()
{
InitializeComponent();
StartCountdown();
}
private void StartCountdown()
{
var startTime = DateTime.Now;
/* the rest of your original label1_Click code goes here ... */
}

Progress bar Start and Stop on Button Click using thread

I have created a C# windows application in that I inserted the progress bar.
When a button is clicked the progress bar should appear and then it should start the process for some 2 to 3 seconds and when the process bar is completed it should be hidden.
I have used this code to solve this but its not working.
While the Progress bar is running, the label box that should be like "Generating... 45%" and after completing the label box should be "Generated 100%..", but when I insert the label its showing some errors.
Here is the picture before clicking the Generate button..
On Processing I Should get like this..
On Final Process id should be like this and the progress bar should hidden..
ProgressBar1.Visible = true;
if (isProcessRunning)
{
MessageBox.Show("A process is already running.");
return;
}
Thread backgroundThread = new Thread(
new ThreadStart(() =>
{
isProcessRunning = true;
for (int n = 0; n < 100; n++)
{
Thread.Sleep(1);
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = n));
}
MessageBox.Show("Generated!!!");
if (progressBar1.InvokeRequired)
progressBar1.BeginInvoke(new Action(() => progressBar1.Value = 0));
isProcessRunning = false;
}
));
// Start the background process thread
backgroundThread.Start();
I suggest you to use BackgroundWorker to show progress bar in C# winform .
Here is an example ,
public partial class Form1 : Form
{
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
label1.Text = "";
label2.Text = "";
}
private void button1_Click_1(object sender, EventArgs e)
{
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
int total = 57; //some number (this is your variable to change)!!
for (int i = 0; i <= total; i++) //some number (total)
{
System.Threading.Thread.Sleep(100);
int percents = (i * 100) / total;
bgw.ReportProgress(percents, i);
//2 arguments:
//1. procenteges (from 0 t0 100) - i do a calcumation
//2. some current value!
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//do the code when bgv completes its work
}
}
You can set your progress bar's visible to false in bgw_RunWorkerCompleted .
The following links will show how to use backgroundworker
DotNetPerls
MSDN Reference
CodeProject
Good Luck :)
This is the Code i am using backgroundWorker..
public partial class Form1 : Form
{
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
label3.Text = "";
this.StartPosition = FormStartPosition.CenterScreen;
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btn_generate_Click(object sender, EventArgs e)
{
progressBar1.Visible = true;
bgw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int total = 100; //some number (this is your variable to change)!!
for (int i = 0; i <= total; i++) //some number (total)
{
System.Threading.Thread.Sleep(10);
int percents = (i * 100) / 100;
bgw.ReportProgress(percents, i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
if (e.ProgressPercentage == 100)
{
label3.Text = String.Format("Generated.. {0} %", e.ProgressPercentage);
}
// label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
}
}`
In this There is a problem in the below code when i click the button for first time the progress bar runs one time and if i clicked second time it runs for 2 times and so on.. other wise the code is perfectly working..
public partial class Form1 : Form {
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
label3.Text = "";
this.StartPosition = FormStartPosition.CenterScreen;
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btn_generate_Click(object sender, EventArgs e)
{ new BackgroundWorker();
progressBar1.Visible = true;
bgw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
bgw.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int total = 100; //some number (this is your variable to change)!!
for (int i = 0; i <= total; i++) //some number (total)
{
System.Threading.Thread.Sleep(10);
int percents = (i * 100) / 100;
bgw.ReportProgress(percents, i);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
if (e.ProgressPercentage == 100)
{
label3.Text = String.Format("Generated.. {0} %", e.ProgressPercentage);
}
// label2.Text = String.Format("Total items transfered: {0}", e.UserState);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
}
}

Using a Progress bar on Form Load

I am trying to Design a WinForms control in C# which will get some data from a database while it's loading.
I want to use a progress bar to show the progress.
I tried this code (and also many others):
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Show();
progressBar1.Value = 10;
int n;
n = 50;//number of records in DB ,
double progress = 0;
double progstep = 25 / n;
for (int i = 1; i <= n; i++)
{
//getting
if (progress <= 100)
progressBar1.Value = (int)progress;
}
progressBar1.Value = 35;
n = 100;//number of records in DB for another data reading from DB ,
progress = 35;
progstep = 65 / n;
for (int i = 1; i <= n; i++)
{
//getting data from DB
dataGridView1.Rows.Add(....);
//Adding that data to a datagrid -- parametrs removed.
progress += progress;
if (progress <= 100)
progressBar1.Value = (int)progress;
}
}
But, the problem is that the form will wait until data reading progress is completed, and I can see just a full progress bar and all data loaded.
What should I do to fix this?
Since this is winforms, i'd recommend using a BackgroundWorker.
Basic example:
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.ProgressChanged += new DoWorkEventHandler(bgWorker_ProgressChanged);
bgWorker.RunWorkerAsync(//pass in object to process)
Which would then kickoff:
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
//Do all of your work here
bgWorker.ReportProgress(); //percent done calculation
}
Then the Progress changed event would fire to update the UI safely:
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}
Add a backgroundWorker1 to your form.
Then add a YourForm_Shown event
private void YourForm_Shown(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
Add on form's constructor after InitializeComponent()
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts.
backgroundWorker1.DoWork += new
DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress.
backgroundWorker1.ProgressChanged += new
ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
And last add the voids of backgroundWorker1:
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
And:
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= n; i++)
{
//getting data from DB.
dataGridView1.Rows.Add(....);
//Adding that data to a datagrid -- parametrs removed.
backgroundWorker1.ReportProgress(i);
// Simulate long task
}
}
This is simple mockup to show you how to work with background worker:
First in your OnLoad create background worker and attach 2 events to it:
var bw = new BackgroundWorker();
bw.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkCompleted);
bw.DoWork += new DoWorkEventHandler(DoWork);
bw.RunWorkerAsync(data); // Assume data is list of numbers.
private void WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
// After work completed remove event handlers and dispose.
{
var bw = (BackgroundWorker)sender;
bw.RunWorkerCompleted -= WorkCompleted;
bw.DoWork -= DoWork; bw.Dispose();
}
private void DoWork(object sender, DoWorkEventArgs e)
{
var data = (List<int>)e.Argument;
foreach (var number in data)
{
if (progressBar1.InvokeRequired)
{
progressBar1.Invoke((MethodInvoker)delegate
{ this.ProcessNumber(number); });
}
else
{
ProcessNumber(number);
}
}
}
private void ProcessNumber(int i)
{
progressBar1.PerformStep();
//do something with i
}
Take a look at BackgroundWorker control. During form load invoke;
backgroundWorker.RunWorkerAsync();
and override event DoWork to do the dirty work (load data from database) and ProgressChanged to update progress bar. In the event body (lets say the event signature will be something like this):
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
var worker = (BackgroundWorker)sender;
// time consuming operation
worker.ReportProgress(10, null);
// ... another stuff
}
private void backgroundWorker_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}

Progress bar or Timer combined

I'm trying to make a timer tick for 80 minutes while the progress bar keeps track of the current time, but the progress bar in C# Forms will not be accurate to the timer ticks. I have it set up for the timer to tick once every 1000 ms and in that tick it will add a step to the progress bar. The progress bar will not act as it should with the timer, does anyone know how to fix this?
public Form1()
{
InitializeComponent();
initTimers();
}
public void timer1_Tick(object sender, EventArgs e)
{
progressBar1.Increment(1);
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Go")
{
timer1.Start();
button1.Text = "Stop";
}
else
{
timer1.Stop();
button1.Text = "Go";
}
}
public void initTimers()
{
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
}
public void progressTimers()
{
progressBar1.Value = 0;
progressBar1.Minimum = 0;
progressBar1.Maximum = 2;
progressBar1.Step = 1;
progressBar1.Visible = true;
}
You need to change this line:
progressBar1.Maximum = 2;
to:
progressBar1.Maximum = 80 * 60; // minutes * 60
And make sure you call progressTimers() :).

Categories

Resources