The Code is given below. it receives filepaths in a list from Form1 and then whole transformation takes place here and everything is working fine BUT the PROBLEM is that progressbar1 does not progress.. what could be the reason? Thanks in advance!
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
numericUpDown1.Enabled = false;
numericUpDown2.Enabled = false;
button1.Enabled = false;
}
List<string> filepath_ = new List<string>();
int count = 0, total = 0;
private string format = string.Empty;
private int _height = 0;
private int _width = 0;
internal void passpath(List<string> fp)
{
filepath_.AddRange(fp);
total = filepath_.Count;
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Stop")
{
backgroundWorker1.CancelAsync();
button1.Text = "Transform";
return;
}
else
{
button1.Text = "Stop";
System.Threading.Thread.Sleep(1);
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
foreach (string filepath in filepath_)
{
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
return;
}
ImageFormat imageFormat = ImageFormat.Jpeg;
switch (format)
{
case "JPEG":
imageFormat = ImageFormat.Jpeg;
break;
break;
default:
break;
}
string finalpath = filepath.Substring(0, filepath.IndexOf('.'));
Image image1 = Image.FromFile(filepath);
string ext = Path.GetExtension(filepath);
if (_height != 0 && _width != 0 && format!=string.Empty)
{
Bitmap bitmap = new Bitmap(image1, _width, _height);
bitmap.Save(finalpath + " (" + _width.ToString() + "x" + _height.ToString() + ")." +format, imageFormat);
}
else if (_height != 0 && _width != 0)
{
Bitmap bitmap = new Bitmap(image1, _width, _height);
bitmap.Save(finalpath + " (" + _width.ToString() + "x" + _height.ToString() + ")" + ext);
}
else if (format != string.Empty)
{
Bitmap bitmap = new Bitmap(image1);
bitmap.Save(finalpath+"." + format, imageFormat);
}
count++;
int i = ((count / total) * 100);
backgroundWorker1.ReportProgress(i);
System.Threading.Thread.Sleep(1);
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label6.Text = count.ToString() + " Out of " + total.ToString() + " Images transformed";
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button1.Text = "Transform";
progressBar1.Value = 0;
if (e.Cancelled)
MessageBox.Show("Transformation stopped. " + count.ToString() + " images transformed.");
else if (e.Error != null)
MessageBox.Show(e.Error.Message);
else
{
MessageBox.Show(count.ToString() + " Images Transformed");
Application.Exit();
}
}
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
format = ((ListBox)sender).SelectedItem.ToString();
button1.Enabled = true;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
_width = 640;
_height = 480;
button1.Enabled = true;
}
}
}
}
Change you variables to doubles:
double count = 0, total = 0;
When you do this calculation:
int i = ((count / total) * 100);
You're currently doing integer arithmetic. The result of count / total (i.e 1 / 10 or 4 / 10) is rounded to 0. When you divide that by 100, the result is still 0, so your ProgressBar won't move.
Using the double type will correctly store the fractional part of your quotient.
The problem had already been pointed out by Grant Winney: It's the integer division.
Without changing data types of count and/or total you could use this:
int i = (int)((100.0 * count) / total)
or that:
int i = (100 * count) / total
where the former makes 100.0 * count a double and the division by total as well. The latter sticks to integer operations by simply multiplying count first (changing sequence of operations), such that the division will not be 0 as long as count is not 0.
pBar.Step = 2;
pBar.PerformStep();
Related
it's my first post here. I'm learning C# (visual studio) at the moment and we have been building a program through given tasks. The last task is to create an "undo" button. This is the code so far:
namespace GestBar_v1._0
{
public partial class Form1 : Form
{
string[] bebidas = { "Café", "Ice Tea", "Água", "Aguardente" };
double[] precoBebidas = { 0.8, 1.5, 1.0, 1.0 };
string[] alimentacao = { "Bolos", "Sandes Mistas", "Torrada", "Salgados" };
double[] precoAlimentacao = { 1.0, 1.5, 1.5, 1.0 };
double soma = 0;
double fecho = 0;
void resetTxt()
{
txtPreco.BackColor = Color.White;
txtPreco.ForeColor = Color.Black;
txtPreco.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Regular);
label2.Text = "Preço Final";
}
private void Processo(string[] items, double[] prices, int itemIndex)
{
if (listaProduto.Items.Contains(items[itemIndex]))
{
int index = listaProduto.Items.IndexOf(items[itemIndex]);
double count = double.Parse(listaUnidade.Items[index].ToString());
listaPreco.Items[index] = Math.Round(prices[itemIndex] * (count + 1), 2);
listaUnidade.Items[index] = count + 1;
soma += prices[itemIndex];
}
else
{
listaProduto.Items.Add(items[itemIndex]);
listaPreco.Items.Add(prices[itemIndex]);
listaUnidade.Items.Add(1);
soma += prices[itemIndex];
}
txtPreco.Text = soma.ToString();
}
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
resetTxt();
btn11.Visible = true;
btn12.Visible = true;
btn13.Visible = true;
btn14.Visible = true;
btn11.Text = bebidas[0] + "\n" + precoBebidas[0] + "€";
btn12.Text = bebidas[1] + "\n" + precoBebidas[1] + "€";
btn13.Text = bebidas[2] + "\n" + precoBebidas[2] + "€";
btn14.Text = bebidas[3] + "\n" + precoBebidas[3] + "€";
btn21.Visible = false;
btn22.Visible = false;
btn23.Visible = false;
btn24.Visible = false;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnAliment_Click(object sender, EventArgs e)
{
resetTxt();
btn21.Visible = true;
btn22.Visible = true;
btn23.Visible = true;
btn24.Visible = true;
btn21.Text = alimentacao[0] + "\n" + precoAlimentacao[0] + "€";
btn22.Text = alimentacao[1] + "\n" + precoAlimentacao[1] + "€";
btn23.Text = alimentacao[2] + "\n" + precoAlimentacao[2] + "€";
btn24.Text = alimentacao[3] + "\n" + precoAlimentacao[3] + "€";
btn11.Visible = false;
btn12.Visible = false;
btn13.Visible = false;
btn14.Visible = false;
}
private void btnTodosP_Click(object sender, EventArgs e)
{
resetTxt();
btn11.Visible = true;
btn12.Visible = true;
btn13.Visible = true;
btn14.Visible = true;
btn21.Visible = true;
btn22.Visible = true;
btn23.Visible = true;
btn24.Visible = true;
btn11.Text = bebidas[0] + "\n" + precoBebidas[0] + "€";
btn12.Text = bebidas[1] + "\n" + precoBebidas[1] + "€";
btn13.Text = bebidas[2] + "\n" + precoBebidas[2] + "€";
btn14.Text = bebidas[3] + "\n" + precoBebidas[3] + "€";
btn21.Text = alimentacao[0] + "\n" + precoAlimentacao[0] + "€";
btn22.Text = alimentacao[1] + "\n" + precoAlimentacao[1] + "€";
btn23.Text = alimentacao[2] + "\n" + precoAlimentacao[2] + "€";
btn24.Text = alimentacao[3] + "\n" + precoAlimentacao[3] + "€";
}
private void btn11_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 0);
}
private void btn12_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 1);
}
private void btn13_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 2);
}
private void btn14_Click(object sender, EventArgs e)
{
resetTxt();
Processo(bebidas, precoBebidas, 3);
}
private void btn21_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 0);
}
private void btn22_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 1);
}
private void btn23_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 2);
}
private void btn24_Click(object sender, EventArgs e)
{
resetTxt();
Processo(alimentacao, precoAlimentacao, 3);
}
private void btnNovo_Click(object sender, EventArgs e)
{
resetTxt();
fecho += Convert.ToDouble(txtPreco.Text);
listaProduto.Items.Clear();
listaPreco.Items.Clear();
listaUnidade.Items.Clear();
txtPreco.Clear();
soma = 0;
}
private void btnRetirarSelec_Click(object sender, EventArgs e)
{
if (listaProduto.SelectedIndex >= 0)
{
int index = listaProduto.SelectedIndex;
double count = double.Parse(listaUnidade.Items[index].ToString());
soma -= count * precoBebidas[index];
listaUnidade.Items.RemoveAt(index);
listaPreco.Items.RemoveAt(index);
listaProduto.Items.RemoveAt(index);
txtPreco.Text = soma.ToString();
}
}
private void btnReduzQnt_Click(object sender, EventArgs e)
{
int index = -1;
if (listaProduto.SelectedIndex >= 0)
{
index = listaProduto.SelectedIndex;
}
else if (listaPreco.SelectedIndex >= 0)
{
index = listaPreco.SelectedIndex;
}
else if (listaUnidade.SelectedIndex >= 0)
{
index = listaUnidade.SelectedIndex;
}
if (index >= 0)
{
double count = double.Parse(listaUnidade.Items[index].ToString());
if (count > 1)
{
soma -= precoBebidas[index];
soma -= precoAlimentacao[index];
listaUnidade.Items[index] = count - 1;
listaPreco.Items[index] = Math.Round(precoBebidas[index] * (count - 1), 2);
listaPreco.Items[index] = Math.Round(precoAlimentacao[index] * (count - 1), 2);
txtPreco.Text = soma.ToString();
}
else
{
listaUnidade.Items.RemoveAt(index);
listaPreco.Items.RemoveAt(index);
listaProduto.Items.RemoveAt(index);
txtPreco.Text = soma.ToString();
}
}
}
private void btnFechoC_Click(object sender, EventArgs e)
{
txtPreco.Text = fecho.ToString();
txtPreco.BackColor = Color.Green;
txtPreco.ForeColor = Color.White;
txtPreco.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Bold);
label2.Text = "Saldo Final";
MessageBox.Show("A caixa foi Encerrada.");
fecho = 0;
}
private void btnReturn_Click(object sender, EventArgs e)
{
}
}
}
I'm sorry about some of the Portuguese elements in the code. Can anyone help out on how to do this? I'm completly lost on this one.
I thought of creating an array and making every button click start by saving the "status quo" to the erray and having it update the listboxes through a button. But I couldn't implement it. The fixed numbers on arrays seems to be the factor.
When you say fixed numbers on arrays, do you mean that it is a hindrance that they can only be of pre-defined sizes?
If that's the case, then use a List. First import the necessary library then create the list, both as shown below:
using System.Collections.Generic;
List<type> myList = new List<type>();
You can add as many items to a list without pre-defining its size.
To append items to the list use:
myList.Append(someData);
To then access the last action made by the user (which you have already appended to the list), use:
type lastAction = myList[-1];
I have this issue with my background worker where it only fires after my task is completed and not during. I have made sure to segment the progress properly but its still not firing. I'm not sure what else I can do.
Here is my code:
private int segmentHalf = 0;
private int segmentFull = 0;
public AutoMaticOne()
{
InitializeComponent();
backgroundWorker.WorkerReportsProgress = true;
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var backgroundWorker = sender as BackgroundWorker;
List<PrintObject> pol = new List<PrintObject>();
var program = programsData.Get(programSelectionInput.Text);
var fields = fieldsData.GetAllByTaskId(program.Id);
pol = printerData.Load(Input, program.Name,fields,program.Delimiter);
pol = pol.OrderBy(x => x.FilePath).ToList();
if (pol != null)
{
for(int i =0;i<pol.Count();i++)
{
segmentHalf = (((i + 1) / pol.Count()) * 100) / 2;
segmentFull = segmentHalf * 2;
backgroundWorker.ReportProgress(segmentHalf);
print.Process(pol[i].FilePath, pol[i].PrinterDriver);
infoInput.Invoke((MethodInvoker)delegate {
infoInput.Text = infoInput.Text + "\r\n" + pol[i].FileName + " - " + pol[i].PrinterDriver;
});
backgroundWorker.ReportProgress(segmentFull);
}
}
}
private void backgroundWorker_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
// Change the value of the ProgressBar to the BackgroundWorker progress.
ProgressBar.Value = e.ProgressPercentage;
ProgressBarLabel.Text = e.ProgressPercentage + "%";
}
private void backgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
InputDirectory.Enabled = true;
OutputDirectory.Enabled = true;
InputDirectoryButton.Enabled = true;
OutputDirectoryButton.Enabled = true;
MessageBox.Show("Task has been Completed, Output files can be found at " + OutputDirectory.Text, "Task Completed");
Start.Enabled = true;
}
When I start with 10 files, it seems fine. But when it loads something like 1000, then it only reports the progress at the end.
SegmentHalf and Full are declared above the constructor
As long as i < pol.Count - 1, (i + 1) / pol.Count will be 0. Integer division truncates towards 0. Your code will execute 0 * 100 for all except the last file.
You can fix it like this:
//segmentHalf = (((i + 1) / pol.Count()) * 100) / 2;
segmentHalf = (((i + 1) * 100) / pol.Count) / 2;
I want to play a video like that guy did [link].
I'm working on C# Windows Form Application (not NXA).
But I don't know how.
I tried using Microsoft.DirectX.AudioVideoPlayback but no luck.
This is what I tried so far :
OpenFileDialog rihanna = new OpenFileDialog();
if(rihanna.ShowDialog() == DialogResult.OK)
{
video = new Video(rihanna.FileName);
video.Owner = panel1;
video.Stop();
}
Now what can i do? I tried using video class but as I said it just did not work.
I'm able to compile but when I'm running the program, I don't see the form window.
using Microsoft.DirectX.AudioVideoPlayback;
namespace Play_Video
{
public partial class Form1 : Form
{
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;
public Form1()
{
InitializeComponent();
VolumeTrackBar.Value = 4;
}
private void timer1_Tick(object sender, EventArgs e)
{
PlayingPosition = CalculateTime(vdo.CurrentPosition);
txtStatus.Text = PlayingPosition + "/" + Duration;
if (vdo.CurrentPosition >= vdo.Duration)
{
timer1.Stop();
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdo.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
else
vdoTrackBar.Value += 1;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.Stop();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
openFileDialog1.Title = "Select video file..";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.DefaultExt = ".avi";
openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
if (openFileDialog1.FileName != "")
{
Form1.ActiveForm.Text = openFileDialog.FileName + " - Anand Media Player";
vdo = new Video(openFileDialog.FileName);
vdo.Owner = panel1;
panel1.Width = 700;
panel1.Height = 390;
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdoTrackBar.Minimum = 0;
vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);
}
}
private void btnPlay_Click(object sender, EventArgs e)
{
if (vdo != null)
{
if (vdo.Playing)
{
vdo.Pause();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
}
else
{
vdo.Play();
timer1.Start();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.pause;
}
}
}
private void btnStop_Click(object sender, EventArgs e)
{
vdo.Stop();
timer1.Stop();
btnPlay.BackgroundImage = Play_Video.Properties.Resources.btnplay;
vdoTrackBar.Value = 0;
}
public string CalculateTime(double Time)
{
string mm, ss, CalculatedTime;
int h, m, s, T;
Time = Math.Round(Time);
T = Convert.ToInt32(Time);
h = (T / 3600);
T = T % 3600;
m = (T / 60);
s = T % 60;
if (m < 10)
mm = string.Format("0{0}", m);
else
mm = m.ToString();
if (s < 10)
ss = string.Format("0{0}", s);
else
ss = s.ToString();
CalculatedTime = string.Format("{0}:{1}:{2}", h, mm, ss);
return CalculatedTime;
}
private void VolumeTrackBar_Scroll(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.Audio.Volume = CalculateVolume();
}
}
public int CalculateVolume()
{
switch (VolumeTrackBar.Value)
{
case 1:
return -1500;
case 2:
return -1000;
case 3:
return -700;
case 4:
return -600;
case 5:
return -500;
case 6:
return -400;
case 7:
return -300;
case 8:
return -200;
case 9:
return -100;
case 10:
return 0;
default:
return -10000;
}
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
}
private void vdoTrackBar_Scroll(object sender, EventArgs e)
{
if (vdo != null)
{
vdo.CurrentPosition = vdoTrackBar.Value;
}
}
private void Form1_Load(object sender, EventArgs e)
{
MaximizeBox = false;
}
private void exitToolItem_Click(object sender,EventArgs e)
{
Application.Exit();
}
}
}
Okey Namespace is clear:
using Microsoft.DirectX.AudioVideoPlayback;
Some Global Variables in Form:
Video vdo;
public string mode="play";
public string PlayingPosition, Duration;
And now in your Button or what else to open:
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
openFileDialog1.Title = "Select video file..";
openFileDialog1.InitialDirectory = Application.StartupPath;
openFileDialog1.DefaultExt = ".avi";
openFileDialog.Filter = "Media Files|*.mpg;*.avi;*.wma;*.mov;*.wav;*.mp2;*.mp3|All Files|*.*";
vdo = new Video(openFileDialog.FileName);
vdo.Owner = panel1;
panel1.Width = 700;
panel1.Height = 390;
Duration = CalculateTime(vdo.Duration);
PlayingPosition = "0:00:00";
txtStatus.Text = PlayingPosition + "/" + Duration;
vdoTrackBar.Minimum = 0;
vdoTrackBar.Maximum = Convert.ToInt32(vdo.Duration);
And in some other Button Code to Start/Pause:
if (vdo.Playing)
{
vdo.Pause();
btnPlay.Text= "Play";
}
else
{
vdo.Play();
btnPlay.Text= "Pause";
}
BTW:
Don't name variables/members or something else in your Code after Girls...
If your aren't sure how to name it, there are some Guidelines here.
The goal is to provide a consistent set of naming
conventions that results in names that make immediate sense to
developers.
For AudioVideoPlayback to work, you'll need to add the AudioVideoPlayback reference, with Reference > Add Reference > Browse > C: > Windows > Microsoft.Net > DirectX for managed code > 1.0.2902.0 > Microsoft.DirectX.AudioVideoPlayback.dll
In this case the progressBar is moving faster then the real Dowork progress then throw exception in the progressChanged event that the progressBar value is over 100% then whats wrong here how do i calculate and report it the right way ?
private List<string> webCrawler(string url, int levels , DoWorkEventArgs eve)
{
bool already = false;
HtmlAgilityPack.HtmlDocument doc;
HtmlWeb hw = new HtmlWeb();
List<string> webSites;// = new List<string>();
List<string> csFiles = new List<string>();
csFiles.Add("temp string to know that something is happening in level = " + levels.ToString());
csFiles.Add("current site name in this level is : " + url);
try
{
doc = hw.Load(url);
webSites = getLinks(doc);
if (levels == 0)
{
return csFiles;
}
else
{
int actual_sites = 0;
for (int i = 0; i < webSites.Count() && i < 20; i++) {
if ((worker.CancellationPending == true))
{
eve.Cancel = true;
break;
}
else
{
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true)) // replace this with future FilterJunkLinks function
{
for (int e = 0; e < csFiles.Count; e++)
{
if (csFiles[e].Contains(t))
{
already = true;
}
}
if (!already)
{
actual_sites++;
csFiles.AddRange(webCrawler(t, levels - 1,eve));
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, "Level Number " + levels + " " + t + Environment.NewLine, Color.Red); }));
worker.ReportProgress(i * 10);
}
}
}
}
return csFiles;
}
}
catch
{
return csFiles;
}
}
public void Texts(RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
worker = sender as BackgroundWorker;
webCrawler(guys, 2,e);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
I passed the variable e of the DoWorkEventsArgs in the DoWork event so i can use the worker variable in the webCrawler function if i need to cancel the operation. In the webCrawler im calling it DoWorkEventArgs eve.
The problem is that the report to the progressBar is not the right way.
Tried the reportprogress as:
for (int i = 0; i < webSites.Count() && i < 20; i++) {
double incPercent = (1 / webSites.Count());
if ((worker.CancellationPending == true))
{
eve.Cancel = true;
break;
}
else
{
string t = webSites[i];
if ((t.StartsWith("http://") == true) || (t.StartsWith("https://") == true)) // replace this with future FilterJunkLinks function
{
for (int e = 0; e < csFiles.Count; e++)
{
if (csFiles[e].Contains(t))
{
already = true;
}
}
if (!already)
{
actual_sites++;
csFiles.AddRange(webCrawler(t, levels - 1,eve));
this.Invoke(new MethodInvoker(delegate { Texts(richTextBox1, "Level Number " + levels + " " + t + Environment.NewLine, Color.Red); }));
worker.ReportProgress(i * (int)incPercent);
worker.ReportProgress(i * 10);
Anytime you have i > 10 (That is, more than 10 pages), you are going over 100% in your progress bar.
If you really wanted to do it by percentage, I would do something like this:
double incPercent = (1 / webSites.Count())
.
.
.
.
worker.ReportProgress(i * incPercent );
As a side note, your variable names and spacing seem.. a little bit off
Edit: Sorry, when performing a division of two numbers and you want the result to be in double, you have to make sure that either divisor or dividend is of type double. Otherwise, you are effectively performing int / int, which gives you an int back. As you probably know, int truncates your decimal points. This is the reason why you had zero in the calculation.
Also, reportProgress method takes values from 0 to 100 so you have to multiply the end result by 100.
Fix your code like this:
double incPercent = (1 / (double)webSites.Count())
.
.
.
.
worker.ReportProgress(i * incPercent * 100 );
I have created a program for some class work and it all works fine, but I'm having some problems with the alignment of the multiple bits of info inserted into the list box on the same rows.
When I print it, it looks messy and also looks messy in the list box.
Is there anyway I can neaten it up a little? I've tried pad right with no joy and list views confuse the hell out of me. Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using System.Collections;
namespace Assignment2
{
public partial class frmCalculator : Form
{
bool blnDot = false;
double dbAllPoints = 0;
double dbAllMoney = 0;
public frmCalculator()
{
InitializeComponent();
}
private void frmCalculator_Load(object sender, EventArgs e)
{
ddbItems.Items.Add("Glass");
ddbItems.Items.Add("Paper");
ddbItems.Items.Add("Beverage Cans");
ddbItems.Items.Add("Tins");
ddbItems.Items.Add("Milk Cartons");
ddbItems.Items.Add("Juice Boxes");
ddbItems.Items.Add("Plastics");
ddbItems.Items.Add("Clothes");
}
private void txtInput_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < '0' || e.KeyChar > '9') && (e.KeyChar != '.'))
{
MessageBox.Show("Please input a number!", "Error");
e.Handled = true;
}
if (e.KeyChar == '.')
{
if (blnDot == true) { e.Handled = true; }
else { blnDot = true; }
}
}
private void txtInput_MouseClick(object sender, MouseEventArgs e)
{
txtInput.Text = "";
}
private void btnCalculate_Click(object sender, EventArgs e)
{
String strItem = "";
double dbMoney = 0;
double dbPoints = 0;
int intPoint = 0;
double dbWeight = 0;
if (((txtInput.Text == "")||(txtInput.Text=="Input the weight")|| (ddbItems.SelectedIndex==0)))
{
MessageBox.Show("Please input a weight into the textbox and make a selection from the drop down box", "Error");
}
else
{
if (ddbItems.SelectedIndex == 1)
{
intPoint = 7;
strItem = ddbItems.Items[1].ToString();
}
if (ddbItems.SelectedIndex == 2)
{
intPoint = 8;
strItem = ddbItems.Items[2].ToString();
}
if (ddbItems.SelectedIndex == 3)
{
intPoint = 10;
strItem = ddbItems.Items[3].ToString();
}
if (ddbItems.SelectedIndex == 4)
{
intPoint = 10;
strItem = ddbItems.Items[4].ToString();
}
if (ddbItems.SelectedIndex == 5)
{
intPoint = 3;
strItem = ddbItems.Items[5].ToString();
}
if (ddbItems.SelectedIndex == 6)
{
intPoint = 3;
strItem = ddbItems.Items[6].ToString();
}
if (ddbItems.SelectedIndex == 7)
{
intPoint = 5;
strItem = ddbItems.Items[7].ToString();
}
if (ddbItems.SelectedIndex == 8)
{
intPoint = 6;
strItem = ddbItems.Items[8].ToString();
}
dbWeight = Convert.ToDouble(txtInput.Text);
dbPoints = intPoint * dbWeight;
dbMoney = dbPoints * 0.01;
dbAllPoints = dbAllPoints + dbPoints;
dbAllMoney = dbAllMoney + dbMoney;
lblTotals.Visible = true;
lblTotals.Text = "You have " + dbAllPoints.ToString() + " points, and you have earned £" + dbAllMoney.ToString("0.00");
lstResults.Items.Add(strItem + " " + dbWeight.ToString() + "kg " + dbPoints.ToString() + " points £" + dbMoney.ToString("0.00"));
txtInput.Text = "Input the weight";
ddbItems.SelectedIndex = 0;
blnDot = false;
}
}
private void btnEnd_Click(object sender, EventArgs e)
{
frmWelcome frmWelcome = (frmWelcome)Application.OpenForms["frmWelcome"];
frmWelcome.Close();
this.Dispose();
}
private void btnReset_Click(object sender, EventArgs e)
{
DialogResult result;
result = MessageBox.Show("Are you sure you want to reset everything?", "Confirm", MessageBoxButtons.YesNo);
if (result == DialogResult.No) return;
txtInput.Text = "Input the weight";
lstResults.Items.Clear();
ddbItems.SelectedIndex = 0;
lblTotals.Text = "";
lblTotals.Visible = false;
blnDot = false;
}
private void btnPrint_Click(object sender, EventArgs e)
{
int intMax;
intMax = lstResults.Items.Count;
String[] arrResults = new String[intMax];
int intLoop;
for (intLoop = 0; intLoop < intMax; intLoop++)
{
arrResults[intLoop] = lstResults.Items[intLoop].ToString();
}
Array.Sort(arrResults);
lstResults.Items.Clear();
for (intLoop = 0; intLoop < intMax; intLoop++)
{
lstResults.Items.Add(arrResults[intLoop]);
}
printDocument1.Print();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
String strLine = "";
int intLoop;
Font pfont = new Font("Verdana", 18, GraphicsUnit.Point);
int intLine = 75;
strLine = "Item Weight Points Money";
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
intLine = intLine + 30;
for (intLoop = 0; intLoop < lstResults.Items.Count; intLoop++)
{
strLine = strLine +lstResults.Items[intLoop];
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
intLine = intLine + 30;
strLine = "";
}
intLine = intLine + 30;
strLine = lblTotals.Text;
e.Graphics.DrawString(strLine, pfont, Brushes.Black, 75, intLine);
strLine = "";
intLine = intLine + 30;
}
}
}
You should use a DataGridView control instead of a ListBox since you are trying to display "column" information.
Likewise, when printing, you should be doing the DrawString for each column as well so that they line up properly.
If you want to continue with what you are doing, then you should use a mono-spaced font like Courier, not Verdana, and count the spaces between then lengths of the words.