Windows forms newbie here, just have a simple question regarding numeric up-down tool.
I have created a program that calculates the cost for car rentals based on size, insurance and discounts. The calculations work fine, however the up-down seems to be "stuck" and shows the values for each day of rental one day behind. For example, if a small size car is $60 per day, and I change the numeric up-down to 2 days, it will show the correct price when 3 days are selected.
Any suggestions on where I've gone wrong would be appreciated.
Code below:
namespace ica3_eventdriven
{
public partial class Form1 : Form
{
const double smallRate = 40.00;
const double midRate = 50.00;
const double sportRate = 60.00;
const double insurance = 15.00;
const double AMA_Discount = 0.1;
int days;
double total;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void tbxName_TextChanged(object sender, EventArgs e)
{
enableControls();
}
private void enableControls()
{
if(tbxName.Text != String.Empty)
{
rbSmall.Enabled = true;
rbMid.Enabled = true;
rbSports.Enabled = true;
cbxInsurance.Enabled = true;
cbxAMA.Enabled = true;
ctrDays.Enabled = true;
}
}
private void rbSmall_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
private void Calculate()
{
int.TryParse(ctrDays.Text, out days);
if (rbSmall.Checked)
{
total = smallRate * days;
labelTotal.Text = total.ToString("c");
if(cbxInsurance.Checked)
{
total = (smallRate * days) + (insurance * days);
labelTotal.Text = total.ToString("c");
}
if(cbxAMA.Checked)
{
total = 0.9 * (smallRate * days);
labelTotal.Text = total.ToString("c");
}
if(cbxInsurance.Checked && cbxAMA.Checked)
{
total = 0.9 * ((smallRate * days) + (insurance * days));
labelTotal.Text = total.ToString("c");
}
}
if (rbMid.Checked)
{
total = midRate * days;
labelTotal.Text = total.ToString("c");
if (cbxInsurance.Checked)
{
total = (midRate * days) + (insurance * days);
labelTotal.Text = total.ToString("c");
}
if (cbxAMA.Checked)
{
total = 0.9 * (midRate * days);
labelTotal.Text = total.ToString("c");
}
if (cbxInsurance.Checked && cbxAMA.Checked)
{
total = 0.9 * ((midRate * days) + (insurance * days));
labelTotal.Text = total.ToString("c");
}
}
if (rbSports.Checked)
{
total = sportRate * days;
labelTotal.Text = total.ToString("c");
if (cbxInsurance.Checked)
{
total = (sportRate * days) + (insurance * days);
labelTotal.Text = total.ToString("c");
}
if (cbxAMA.Checked)
{
total = 0.9 * (sportRate * days);
labelTotal.Text = total.ToString("c");
}
if (cbxInsurance.Checked && cbxAMA.Checked)
{
total = 0.9 * ((sportRate * days) + (insurance * days));
labelTotal.Text = total.ToString("c");
}
}
}
private void ctrDays_ValueChanged(object sender, EventArgs e)
{
Calculate();
}
private void cbxInsurance_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
private void cbxAMA_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
private void rbMid_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
private void rbSports_CheckedChanged(object sender, EventArgs e)
{
Calculate();
}
}
}
Related
So I have an invoice total form that should calculate the percentage discount among other things. I'm adding a second form to the code that allows you to change the sales tax I got it to populate the form and actually work with no errors but I can't get it to move the data from the textbox on frmSalesTax to the txtSalesTax.Text in frmInvoiceTotal.
frmInvoiceTotal Code:
public frmInvoiceTotal()
{
InitializeComponent();
}
frmSalesTax percent = new frmSalesTax();
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal productTotal = Convert.ToDecimal(txtProductTotal.Text);
decimal salesTax = (7.75m/100m) * productTotal;
decimal discountPercent = .0m;
if (productTotal < 100)
discountPercent = .0m;
else if (productTotal >= 100 && productTotal < 250)
discountPercent = .1m;
else if (productTotal >= 250)
discountPercent = .25m;
decimal discountAmount = (productTotal + salesTax) * discountPercent;
decimal subtotal = productTotal - discountAmount;
decimal invoiceTotal = (subtotal + salesTax) - discountAmount;
txtSubtotal.Text = subtotal.ToString("c");
txtSalesTax.Text = salesTax.ToString("c");
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString("c");
txtTotal.Text = invoiceTotal.ToString("c");
txtProductTotal.Focus();
}
private void btnChange_Click(object sender, EventArgs e)
{
percent.salesTax = txtSalesTax.Text;
switch (percent.ShowDialog())
{
case DialogResult.OK:
txtSalesTax.Text = percent.salesTax;
break;
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
invoiceTotal GUI:
frmSalesTax Code:
public partial class frmSalesTax : Form
{
public string salesTax
{
get;
set;
}
public frmSalesTax()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOk_Click(object sender, EventArgs e)
{
this.salesTax = txtPercent.Text;
txtPercent.Text = "";
Hide();
}
I know I'm missing something but I can't figure out what it is.
salesTax GUI:
You've got the right idea making a property on frmSalesTax to communicate...but you're not really using it.
In your frmInvoiceTotal, you need to send the current value to frmSalesTax.salesTax and then handle the results of the percent dialog returning DialogResult.OK:
private void btnChange_Click(object sender, EventArgs e)
{
percent.salesTax = txtSalesTax.Text; //--> send current value to frmSalesTax
switch ( percent.ShowDialog() ) //--> ShowDialog will return the DialogResult of the pressed button
{
case DialogResult.OK:
txtSalesTax.Text = percent.salesTax; //--> update with new value from frmSalesTax
break;
}
}
...and, in your frmSalesTax, you need to put the txtPercent.Text into the salesTax property when the user clicks the OK button:
private void btnOk_Click(object sender, EventArgs e)
{
this.salesTax = txtPercent.Text; //--> frmInvoiceTotal will read this after the OK button is clicked
txtPercent.Text = "";
Hide();
}
Important: you have to make sure the frmSalesTax buttons have their DialogResult set, so that frmInvoiceTotal.btnOk_Click knows that it's okay to get the value:
Edit
The property (in frmSalesTax) needs to not be based on the form's text values...because you're setting that to "" when the form hides. This is what you want for the property:
public string salesTax
{
get;
set;
}
This would go with the other changes I mentioned earlier.
Edit 2
It's easy to get frustrated. There are a lot of moving pieces, and I can understand how the eyes can cross. Here's the crux of the issue - your calculation is trashing things on you;-)
These lines in the btnCalculate_Click:
decimal salesTax = (7.75m/100m) * productTotal;
decimal discountPercent = .0m;
//...
txtSalesTax.Text = salesTax.ToString("c");
txtDiscountPercent.Text = discountPercent.ToString("p1");
...should be the initial values and come in the form's initialization code:
public frmInvoiceTotal()
{
InitializeComponent();
decimal salesTax = (7.75m/100m) * productTotal;
decimal discountPercent = .0m;
txtSalesTax.Text = salesTax.ToString("c"); //--> the initial value
txtDiscountPercent.Text = discountPercent.ToString("p1");
}
...and then, the calculation should not re-populate txtSalesTax.Text or txtDiscountPercent.Text. The txtSalesTax.Text might be update from showing frmSalesTax, and I'm guessing you're gonna make another form to override discount percent at some point.
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal productTotal = Convert.ToDecimal(txtProductTotal.Text);
decimal salesTax = Convert.ToDecimal(salesTax.Text) * productTotal; //--> if it got changed in frmSalesTax
decimal discountPercent = .0m;
if (productTotal < 100)
discountPercent = .0m;
else if (productTotal >= 100 && productTotal < 250)
discountPercent = .1m;
else if (productTotal >= 250)
discountPercent = .25m;
decimal discountAmount = (productTotal + salesTax) * discountPercent;
decimal subtotal = productTotal - discountAmount;
decimal invoiceTotal = (subtotal + salesTax) - discountAmount;
txtSubtotal.Text = subtotal.ToString("c");
//txtSalesTax.Text = salesTax.ToString("c"); //--> don't do this...it steps on what came from frmSalesTax
//txtDiscountPercent.Text = discountPercent.ToString("p1"); //--> when you add another form to override this
txtDiscountAmount.Text = discountAmount.ToString("c");
txtTotal.Text = invoiceTotal.ToString("c");
txtProductTotal.Focus();
}
I bet this get you a lot closer :-)
i'm doing a "shutdowner" project in WinForm.
I can enter there a amount of minutes, after these minutes the pc shutdown.
Now i create a progressbar, min Value of 0, Max Value of 100.
e.g:
I enter 3 minutes (180 sec), and click on a "start" button, the value should be 0, and it should be 100 when the PC shutdowns (after the entered minutes).
I tried some math, but i didn't got it to work.
Thanks for you help!
Try something like...
private int totalSeconds;
private DateTime targetTime;
private void button1_Click(object sender, EventArgs e)
{
int mins = (int)numericUpDown1.Value;
if (mins > 0)
{
TimeSpan ts = TimeSpan.FromMinutes(mins);
targetTime = DateTime.Now.Add(ts);
totalSeconds = (int)ts.TotalSeconds;
progressBar1.Value = 0;
button1.Enabled = false;
timer1.Interval = 1000;
timer1.Start();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = targetTime.Subtract(DateTime.Now);
if (ts.TotalMilliseconds > 0)
{
label1.Text = "-" + ts.ToString(#"mm\:ss");
double percent = ((double)totalSeconds - ts.TotalSeconds) / (double)totalSeconds;
progressBar1.Value = (int)(progressBar1.Maximum * percent);
}
else
{
timer1.Stop();
button1.Enabled = true;
progressBar1.Value = progressBar1.Maximum;
// ... do something here! ...
}
}
I'm creating a program that allows the user to choose 2 different options, 1 for the dormitories and 1 for the meal plan. I'm using radio buttons for both, but I can only choose 1 button at a time, and I want to be able to choose both at the same time
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
int totalCharge = 0;
totalCharge = Dorm() + MealPlan();
Form1 TChargeForm = new Form1();
TChargeForm.label1.Text = totalCharge.ToString("c");
TChargeForm.ShowDialog();
}
private void button3_Click(object sender, EventArgs e)
{
radioButton1.Checked = false;
radioButton2.Checked = false;
radioButton3.Checked = false;
radioButton4.Checked = false;
radioButton5.Checked = false;
radioButton6.Checked = false;
radioButton7.Checked = false;
}
private int Dorm()
{
int total = 0;
if (radioButton1.Checked)
{
total += 1500;
return total;
}
if (radioButton2.Checked)
{
total += 1600;
return total;
}
if (radioButton3.Checked)
{
total += 1500;
return total;
}
if (radioButton4.Checked)
{
total += 1500;
return total;
}
else
{
return total;
}
}
private int MealPlan()
{
int total = 0;
if (radioButton5.Checked)
{
total += 600;
return total;
}
if (radioButton6.Checked)
{
total += 1200;
return total;
}
if (radioButton7.Checked)
{
total += 1700;
return total;
}
else
{
return total;
}
}
}
Try using the GroupName property for each type of button: dorimitories, mealplan
Groupname attribute allows you to create logical groups of selections for radio buttons.
Add this attribute to every radio button or at the group box level.
I am trying to calculate the "change" due at the end of my program into a MessageBox. The Dollar amount entered into a text box needs to have the total subtracted from it but I just can't seem to see what I am doing wrong. Can anyone help me finish this?
namespace HardwareStore
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
ProductBox.Items.Add(new Hardware() { ItemNo = 1010, ProdName = "Hammer ", Price = (decimal)14.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 1056, ProdName = "Bag of Nails ", Price = (decimal)19.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 2001, ProdName = "Saw ", Price = (decimal)29.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 2005, ProdName = "Chainsaw ", Price = (decimal)69.99d });
ProductBox.Items.Add(new Hardware() { ItemNo = 3090, ProdName = "Ladder ", Price = (decimal)109.99d });
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnAddItem_Click(object sender, EventArgs e)
{
try
{
for (int i = 0; i < int.Parse(txtQuantity.Text); i++)
ReceiptBox.Items.Add(ProductBox.Items[ProductBox.SelectedIndex]);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReceiptBox_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);
decimal tax = Math.Round((subTotal * .075M), 2);
decimal total = subTotal + tax;
lblSub.Text = "$" + subTotal.ToString();
lblTax.Text = "$" + tax.ToString();
lblTotal.Text = "$" + total.ToString();
lblSub.Visible = true;
lblTax.Visible = true;
lblTotal.Visible = true;
}
private void btnChange_Click(object sender, EventArgs e)
{
MessageBox.Show("Change Due: $ ");
}
}
}
I think I caught it twice...
decimal total = 0; //declare the total as global variable
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal subTotal = ReceiptBox.Items.Cast<Hardware>().Sum(item => item.Price);
decimal tax = Math.Round((subTotal * .075M), 2);
total = subTotal + tax;
lblSub.Text = "$" + subTotal.ToString();
lblTax.Text = "$" + tax.ToString();
lblTotal.Text = "$" + total.ToString();
lblSub.Visible = true;
lblTax.Visible = true;
lblTotal.Visible = true;
}
private void btnChange_Click(object sender, EventArgs e)
{
decimal customerPay = 100;
if (total != 0){
decimal changeDue = customerPay - total;
txtDollar.Txt = "$ " + changeDue.toString();
MessageBox.Show("Change Due: " + txtDollar.Txt);
}
}
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();