How to set value of progress bar - c#

I have written a user control using C# Winforms. In the user control, I have three textboxes:
txtStartNumber - input is of type: int.
txtEndNumber - input is of type: int.
txtQuantity - iput is of type: int. (value = txtEndNumber - txtStartNumber)
The progress bar denotes the no. of records added to the database and its total range is set to be equal to txtQuantity.
When one or more records are duplicate, the progress bar is stopped.
My questions are:
How to set the initial value of the progress bar?
How to manage the progress shown by progress bar?
How I save it to the database:
for (long i = from; i < to; i++)
{
for (int j = 0; j < (to - from); j++)
{
arrCardNum[j] = from + j;
string r = arrCardNum[j].ToString();
try
{
sp.SaveCards(r, 2, card_Type_ID, SaveDate, 2);
progressBar1.Value = j;
}
}
}

Try this:
private void StartBackgroundWork() {
if (Application.RenderWithVisualStyles)
progressBar.Style = ProgressBarStyle.Marquee;
else {
progressBar.Style = ProgressBarStyle.Continuous;
progressBar.Maximum = 100;
progressBar.Value = 0;
timer.Enabled = true;
}
backgroundWorker.RunWorkerAsync();
}
private void timer_Tick(object sender, EventArgs e) {
progressBar.Value += 5;
if (progressBar.Value > 120)
progressBar.Value = 0;
}
The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress.
Here is another Progress Bar Tutorial

You can't use loop to do this with progressbar. There is a difference between running code in for, while, do...while loops or in timers. In loops code is immediately done and you can't see this, in timers you can. Even if you try to put in loops if counters, it will not works:
for(int i=a;i<b;++i)
{
if (cnt < 1000000)
{
IncrProgressBar();
cnt++;
}
else
{
cnt = 0;
}
}
If you want to use progressbar to do this then you must put in timer OnTick event code that adds data to database, and in this event increment progressbar value. It's similarly with changing form component's other properties (Text, Size, ...). If you want to see change on component you must use timers.

To change the value use:
private void timer1_Tick(object sender, EventArgs e)
{
progressBar2.Value = progressBar2.Value - 15;
}
In C#

Related

Progress Bar Do Work Backgroundworker C# WinForms

hope anybody can help me. My problem is the progress bar in C# WinForms. I have the following Code:
(There is a stupid calculate from an uint until a given number from a textbox and i want to show the progress while the calculate method is running)
// The stupid method which calculate
public void ueberlaufUint()
{
try
{
uint ueberlaufZahl = Convert.ToUInt32(textBox1.Text);
do
{
ueberlaufZahl++;
//Console.WriteLine(ueberlaufZahl);
} while (ueberlaufZahl <= 100);
label1.Text = "Endzahl: " + ueberlaufZahl;
}
catch (Exception)
{
MessageBox.Show("Only not negative natural numbers accepted");
}
}
// Buttonclickevent
private async void button1_Click(object sender, EventArgs e)
{
ueberlaufUint();
progressBar1.Maximum = 100;
progressBar1.Step = 1;
var progress = new Progress<int>(v =>
{
// This lambda is executed in context of UI thread,
// so it can safely update form controls
progressBar1.Value = v;
});
// Run operation in another thread
await Task.Run(() => DoWork(progress));
}
// DoWork
public void DoWork(IProgress<int> progress)
{
// This method is executed in the context of
// another thread (different than the main UI thread),
// so use only thread-safe code
for (int j = 0; j < 10000; j++)
{
ueberlaufUint();
// Use progress to notify UI thread that progress has
// changed
if (progress != null)
progress.Report((j + 1) * 100 / 100000);
}
}
The progressbar only counts few steps with no dependency (in my meaning) with the calculate method.
Very great thanks in forward, sorry for my bad english.
Just a typo. You have an extra 0 in the code:
progress.Report((j + 1) * 100 / 100000);
should be
progress.Report((j + 1) * 100 / 10000);

C# Label text not updating while Progress bar value is

In C# im trying to make a little game type program and im trying to make a loading bar that uses the Progress bar and the text is using a Label, for example the Progress bar is 1 - 25 and i want the label text to update while the bar is, heres an example:
private void StartLoading_Click(object sender, EventArgs e)
{
MainProgressBar.Maximum = 25;
int P = 0;
while (P < 25)
{
// Delay
System.Threading.Thread.Sleep(130);
// Increase Progress
P++;
// Set Progress Bar Value
MainProgressBar.Value = P;
// Set Text Above Progress Bar
LoadingText.Text = P + "/25";
}
}
Ps. I dont want some Huge code, i want it to be simple like this
State of the art is this snippet for you:
private void StartLoading_Click(object sender, EventArgs e)
{
const int max = 25;
var progressHandler = new Progress<int>(value=>{
LoadingText.Text = value + "/" + max;
MainProgressBar.Value = value;
});
var progress = progressHandler as IProgress<int>;
await Task.Run(() =>
{
int P = 0;
while (P < 25)
{
Thread.Sleep(130);
progress?.Report(++P);
}
}
}
This processes your long running task (Sleep in this case), in a seperate Thread and reuse the value via the Progress-Class. This way your GUI is updated in GUI-Thread as recommended and you will get the updates accordingly. Further it's not recommended to use Application.DoEvents();, because there are many pitfalls you have to know about.

Windows Form App for loop not working

int i = 0;
private void button1_Click(object sender, EventArgs e)
{
for (int j = 10; j < 1000; j = j + 1)
{
string y = i.ToString();
webBrowser1.Document.GetElementById("lst-ib").SetAttribute("value", y);
i++;
}
}
This is the section of code I'm working with in a windows form application
I want it to input the value and show it going up however it just jumps to the end and puts the last output instead of counting up.
Some people said to use timers but I haven't been able to get them to work.
Any ideas?
You're locking up the UI thread with your loop, so that it doesn't update the control until it's done with its work. You end up only seeing the final value, when the loop is complete and the UI refreshes.
Take a look at using a Timer control instead. You can tell it to raise an event at regular intervals, and it'll allow your UI to be updated correctly.
Add a Timer to your Form and then insert the following code into your constructor to try it out. Currently, it updates your element every 1 ms (in reality, it won't be that fast).
int i = 0;
int j = 10;
timer1.Interval = 1;
timer1.Tick += (s, e) =>
{
string y = i.ToString();
webBrowser1.Document.GetElementById("lst-ib").SetAttribute("value", y);
i++;
j++;
if (j > 1000)
timer1.Stop();
};
timer1.Start();

Adding percentage text to progressbar C#

I have a method that shows when a process bar is in execution and when is successfully completed.
I worked fine, but I would like to add a percentage showing a 100% if is complete and less if it got stuck some where.
I have made several research online but I could not adapt anything to the solution that I am looking for.
This is my code:
private void progressBar()
{
int i;
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
for (i = 0; i <= 100; i++)
{
progressBar1.Value = i;
}
}
I use the method call on my execution button by calling it with the follow:
progressBar();
Thanks
I have adjust the prograssBar method with the following lines.
The solution works.
Thanks
int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
progressBar1.Refresh();
progressBar1.CreateGraphics().DrawString(percent.ToString() + "%",
new Font("Arial", (float)8.25, FontStyle.Regular),
Brushes.Black,
new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
In order to implement the progress in your operation, the operation's length must be calculated first. if it's not possible, you can't show a progress bar for that operation. (maybe only a loading gif)
but if so, There is an interface (IProgress) which can help you implement the progress reports.
First thing you should know, You must do the main task on another thread, and report the progress to the UI Thread. a simple example of this work would be something like this.
Progress.cs
public class Progress<T> : IProgress<T>
{
private readonly Action<T> _progressAction;
public Progress(Action<T> action)
{
_progressAction = action;
}
public void Report(T value)
{
_progressAction?.Invoke(value);
}
}
Your code would be like this, in which the task starts after you click a button named ButtonBase
Progress<int> MyProgressObject { get; set; }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
MyProgressObject = new Progress<int>(ProgressAction);
ThreadPool.QueueUserWorkItem(TimeConsumingTask);
}
public void TimeConsumingTask(object state)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
MyProgressBar.Dispatcher.Invoke(() => ProgressAction(i));
}
}
public void ProgressAction(int progress)
{
MyProgressBar.Value = progress;
}
I know It might look difficult but this is the proper way of doing time consuming tasks and prevent UI block
If you use it as a part of backgroundworker it works perfectly
I added a Label in the middle of the progressbar
And i added last row in my bgw_ProgressChanged method
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
p_bar.Value = e.ProgressPercentage;
fnameLbl.Text = e.UserState.ToString();
percentLbl.Text = "%" + (e.ProgressPercentage).ToString();
}
ProgressPercentagevalue comes from the method below
foreach (var item in filebox1)
{
System.IO.File.Move(item, Path.Combine(destdir, Path.GetFileName(item)));
++counter;
int tmp = (int)((counter* 100) / totfiles);
bgw.ReportProgress(tmp, "File transfered : " + Path.GetFileName(item));
Thread.Sleep(100);
}
Totfiles is the number of files that I get from server.
Thread.Sleep(100) let's you see for a short time what is displayed with fnameLbl.Text
int total = ;
int val = ;
double createDivider = total / 100;
int percent = val / createDivider;
this value (percent) is the right percent '%' of total

is there any possible way to store temporary integer value in c# 4.5?

I am creating WPF application. I need to store a temporary value in some variable in one method and I need to get back that value in another method. is there any possible way to store the temporary value in a variable using WPF?
From Comment:
private void Button_Click(object sender, RoutedEventArgs e)
{
count++;
for (int i = 1; i <= count; i++)
{
var tb = new TextBox();
mycanvas.Children.Add(tb);
tb.Name = "txtbox"+i;
tb.Width = 100;
Canvas.SetLeft(tb,50);
Canvas.SetTop(tb, i*20);
}
}
I think you're having a bit of a misunderstanding here ...
WPF (Windows Presentation Foundation), is a technology that came to replace WinForms ...
Storing temp integers would be done exactly like it'll be done in WinForms, Console application or a dll.
You'll save it as a variable that the other method can see (depending on where it is), or send it as a parameter.
If you're talking about MVVM, things get a bit more interesting, but you can still store and send temp variables ...
Having said that, you can also stash away variables in the application settings, and use them (or their default values you can set) however you want. Here's more on this option: MSDN: Application Settings Overview
.
If you want to do something on every i, Jossef Harush is on the money, otherwise (or in addition, you can do something like the following as well:
private int global_variable_name;
private void Button_Click(object sender, RoutedEventArgs e)
{
count++;
for (int i = 1; i <= count; i++)
{
var tb = new TextBox();
mycanvas.Children.Add(tb);
tb.Name = "txtbox"+i;
tb.Width = 100;
Canvas.SetLeft(tb,50);
Canvas.SetTop(tb, i*20);
// You can set global_variable_name here, but it'll be
// silly to set it to `i`, since it's changing
global_variable_name = 8;
}
}
private void SomeOtherMethod() {
// you can use global_variable_name here
var sum = global_variable_name + 3;
}
Welcome you to StackOverflow, i agree with #Noctis answer.
In addition (after reading your comment),
If you would like to pass the current loop's index to a custom method, this is what you should do:
private void Button_Click(object sender, RoutedEventArgs e)
{
int count = 10;
count++;
for (int i = 1; i <= count; i++)
{
var tb = new TextBox();
mycanvas.Children.Add(tb);
tb.Name = "txtbox" + i;
tb.Width = 100;
Canvas.SetLeft(tb, 50);
Canvas.SetTop(tb, i * 20);
// My custom method
MyMethod(i);
}
}
private void MyMethod(int i)
{
// Do something with i
Console.WriteLine(i);
}

Categories