i wanted to make every 30 percent in progress bar, the text changes.
What i wanted to do is, when the progress bar hit 25 percent, the text changes and it stop for a second, and it goes back to 50, and the text changes again, it keep going until it hit 100 percent.
Here is my code:
public WelcomeScreen()
{
InitializeComponent();
_timer.Interval = 2000;
label1.ForeColor = Color.White;
}
private void WelcomeScreen_Load(object sender, EventArgs e)
{
var worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerAsync();
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var percentComplete = e.ProgressPercentage;
var userState = (string)e.UserState;
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = 100;
progressBar1.Step = 25;
if (progressBar1.Step <= 25)
{
label1.Text = "Preparing Setup";
}
else if (progressBar1.Step <= 50)
{
label1.Text = "Preparing Application";
}
else if (progressBar1.Step <= 75)
{
label1.Text = "Preparing Database";
}
else if (progressBar1.Step <= 100)
{
label1.Text = "Preparing Contents";
}
else
{
label1.Text = "Launch Application";
}
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_timer.Enabled = true;
_timer.Tick += new EventHandler(Timer_Tick);
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
var currentWorker = (BackgroundWorker)sender;
currentWorker.ReportProgress(0, "Preparing Setup");
currentWorker.ReportProgress(25, "Preparing Application");
currentWorker.ReportProgress(50, "Preparing Database");
currentWorker.ReportProgress(75, "Preparing Contents");
currentWorker.ReportProgress(100, "Launch Application");
}
void Timer_Tick(object sender, EventArgs e)
{
_timer.Enabled = false;
this.Hide();
_login.ShowDialog();
this.Close();
}
When the progress bar hit 100 percent, i order the application to wait until 2 seconds before show another form after the text changes to "Launch Application".
All the code in your WelcomeScreen_Load will block the UI thread until it is complete. This means that no matter what you do to your progress bar, it will never show it's changes until it is complete (which it will "jump" to the last settings).
You will want to look into Background Workers. These let you do your code async, and report back every-so-often with what the current state is (ie: the percent complete).
So, a really short example:
private void WelcomeScreen_Load(object sender, EventArgs e)
{
var worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.ProgressChanged += worker_ProgressChanged;
worker.RunWorkerAsync();
}
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
var percentComplete = e.ProgressPercentage;
var userState = (string)e.UserState;
//do something with these values, like moving your progress bar
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
progressBar1.Value = percentComplete;
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// do something when the worker completes, like start your timer
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
// do the "work" for the background worker
var currentWorker = (BackgroundWorker)sender;
currentWorker.ReportProgress(0, "Just Starting");
// do your first task
currentWorker.ReportProgress(25, "Finish First Task");
// ...
}
Related
So I have a quick file mover program and it works fine and the progress bar show the right percentage while working but when i run it a second time. The progress bar starts at the last value. Even though I start by updating the progressbar1.value = 0;
Only way to make the progressbar re-start at zero is to close the program and start it again
private void button_move_Click(object sender, RoutedEventArgs e)
{
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(Worker_ProgressChanged);
worker.WorkerReportsProgress = true;
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Worker_RunWorkerCompleted);
worker.RunWorkerAsync();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
//neither updating the Value to 0 or ReportProgress to 0 worked
//progressbar1.Value = 0;
//worker.ReportProgress(0);
moveFiles(sender, e, dirFiless);
}
catch (Exception ex)
{
Console.WriteLine("Error trying to Move files: " + ex);
}
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressbar1.Value = e.ProgressPercentage;
progressbar1.Value = e.ProgressPercentage - 1;
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressbar1.Value = 0;
return;
}
//this works and the progress bar gets updated incrementally
public void moveFiles(object sender, DoWorkEventArgs e, string[] dirFiles)
{
totalFiles = dirFiles.Length;
foreach (string file in dirFiles)
{
filecount++;
percentage = (int)((filecount * 100) / totalFiles);
worker.ReportProgress(percentage);
//move file
}
worker.ReportProgress(100);
}
Are you resetting your filecount variable back to 0? In the code you posted it appears that it just keeps counting up with each run which would cause the progress bar to jump back up even after you previously set it back to 0.
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
}
}
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;
}
}
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;
}
I'm trying to make a progressbar advance using a BackgroundWorker. The final goal is to show the progress of a background search, but I first want to get to know the progress bar by doing a simple simulation. This is the code:
public MainWindow()
{
InitializeComponent();
worker = new BackgroundWorker(); // variable declared in the class
worker.WorkerReportsProgress = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Title += " DONE";
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
for(int j = 0; j <= 100; j++)
{
worker.ReportProgress(j);
Title += j.ToString();
Thread.Sleep(50);
}
}
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
searchProgressBar.Value = e.ProgressPercentage;
}
But when I run it, it skips right to the end, without altering the progressbar in any way. When I debug it step-by-step, the last step I get to is worker.ReportProgress(j);, then control returns to the program and worker_RunWorkerCompleted is called. Why?
In case you trying to change the UI content, you should put the calls on UI Dispatcher. You can't modify UI objects from background thread. Replace your lines with these -
App.Current.Dispatcher.Invoke((Action)delegate()
{
Title += j.ToString();
});
and
App.Current.Dispatcher.Invoke((Action)delegate()
{
Title = "Done";
});
You forgot to run the worker:
worker.RunWorkerAsync();