Konstantin  Mokhov
Konstantin Mokhov

Reputation: 127

ProgressBar decimal value

I have a cycle. the number of iterations depends on the choice of the user. I get the number of double, but the progress bar only accepts int;

double progr = 100 / (listBox2.Items.Count * listBox4.Items.Count);
progressBar1.Value += progr; <-

Upvotes: 1

Views: 7341

Answers (2)

user287107
user287107

Reputation: 9417

if you want to use a progressbar to show the processing of TotalCount_n items, you would typically use this statements:

progressBar1.Maximum = TotalCount_n;
progressBar1.Value = currentItem;

if you have two processes, like TotalCount_n and TotalCount_m, you can write

progressBar1.Maximum = TotalCount_n * TotalCount_m;
progressBar1.Value = currentItem_n * TotalCount_m + currentItem_m;

if you want to calculate a percentage with an int, you can write:

int percentage = (currentItem * 100) / TotalCount_n;

if you have a processbar showing percentages, then you use

//progressBar1.Maximum = 100; // set in the designer
progressBar1.Value = (currentItem * 100) / TotalCount_n;

if you have a processbar with a random maximum, you can also write:

progressBar1.Value = (currentItem * progressBar1.Maximum) / TotalCount_n;

but then you need to take care, that the numbers wont get too high. so if TotalCount_n and the maximum is both higher than 65000, you will get an overflow because the product currentItem * progressBar1.Maximum might get over 2^32.

Upvotes: 5

leppie
leppie

Reputation: 117260

double progr = 100 / (listBox2.Items.Count * listBox4.Items.Count);
progressBar1.Value += progr; 

Issues detected in those 2 lines:

  1. Possible division by zero
  2. Integer division and assignment to double
  3. Assignment of double to integer property
  4. Use of increment instead of assignment to Value
  5. Incorrect division to determine progress (operands are swapped)

Upvotes: 1

Related Questions