I'm new to C# and I'm trying to do a simple task. I'm trying to make an if statement for my program where if the user enters a number less than 100, it multiplies by .1 and shows the answer in a message box. But everytime I run the program the message box gives me back 0 for an answer rather than 6.5 for 65 for example. I am probably just missing something easy in my code here, please take a look.
public partial class Form1 : Form
{
private double discountAmt;
public Form1()
{
InitializeComponent();
}
private void DiscountCalculation(object sender, EventArgs e)
{
double Price = 0;
double.Parse(PriceBox.Text);
if (Price < 100)
{
discountAmt = (Price * .1);
MessageBox.Show(" The discount is " + discountAmt.ToString());
}
}
}
}
Look at this line:
double.Parse(PriceBox.Text);
It parses the textbox, but doesn't do anything with the result. You want this:
double Price = double.Parse(PriceBox.Text);
Even better is to use double.TryParse(), and also when working with money use the decimal type rather than double.
private void DiscountCalculation(object sender, EventArgs e)
{
decimal Price = 0.0m;
if (decimal.TryParse(PriceBox.Text, out Price) && Price < 100)
{
discountAmt = (Price * .1);
MessageBox.Show($"The discount is {discountAmt}");
}
}
Related
I have a C# WPF app, and my goal is to get the sum of selected row values from a DataGrid, and set a textbox with this total. This sum calculation is triggered by an event that detects when the selected items have changed.
The problem is that when I select many rows at once or select all with Ctrl + A, I get unpredictable sum values.
To troubleshoot, I bound the datagrid with 100 rows, each with an amount of 1. I then selected all items with Ctrl + A. The total sum should be 100, but it caps at 7 or 8 units.
Below is what I have so far. Anyone see the problem?
private void DgDailyTransactions_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
decimal sum = 0;
for (int i = 0; i < dgDailyTransactions.SelectedItems.Count; i++)
{
TextBlock tb = dgDailyTransactions.Columns[1].GetCellContent(dgDailyTransactions.SelectedItems[i]) as TextBlock;
if (tb != null)
{
sum += Convert.ToDecimal(tb.Text);
}
}
tbxSelectedDailyTransactionsTotal.Text = sum.ToString();
}
Suppose your class looks like this:
public class Sales
{
public int Order { get; set; }
public decimal Amount { get; set; }
}
Make a simple method as under:
private void FindAmount()
{
decimal totalSum = 0;
//Add amounts of selected
if (MyDTGRID.SelectedItems.Count > 0)
{
for (int i = 0; i <= dgDailyTransactions.SelectedItems.Count - 1; i++)
{
Sales sales = dgDailyTransactions.SelectedItems[i] as Sales;
decimal amount = sales.Amount;
totalSum += amount;
}
}
myTextBlock.Text = totalSum.ToString();
}
Simply call the method in your selectedCellsChanged Event
private void DgDailyTransactions_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
FindAmount();
}
I hope this helps.
for the sum method you can do it using linq (if you don't know I strongly advise you to learn linq, very strong tool in C#), also would advise you to use MVVM, will make your code much easier to debug in future :
private void dgDailyTransactions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
List<Sales> myList=dgDailyTransactions.SelectedItems.Cast<Sales>();
decimal totalSum = 0;
if (myList.Count() > 0)
{
totalSum = myList.Sum(item => item.Amount);
}
myTextBlock.Text = totalSum.ToString();
}
in MVVM (if you use it) you would need just that line in Model :
private void dgDailyTransactions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
contexte.SelectedSales= new ObservableCollection<Sales>(dgDailyTransactions.SelectedItems.Cast<Affaire>());
}
then you use formula in your ViewModel in set section of SelectedSales
I'm trying to update values in read-only text boxes "Number of Months" and "Balance" after each click. In the given context both of these should have a starting value of 0 when the application begins. They should be updated after each click with the number of months simply adding up (1, 2, 3, etc.). The balance should show a specific value added up with each click.
The balance is equal to the monthly savings amount with the return of interest compounded monthly, so it would be dependent on the amount of months generated after each click.
I can make the month counter tick after each click as you'll see in the code, but I can't figure out how to update the balance and display it after each activation of the "Next Month" button.
public partial class frmSavingsCalculator : Form
{
public frmSavingsCalculator()
{
InitializeComponent();
}
int months = 0;
double balance = 0;
private void btnNext_Click(object sender, EventArgs e)
{
double monthlypmt;
int annualrate;
if (double.TryParse(txtMonthlySavings.Text, out monthlypmt))
{
if (int.TryParse(txtAnnualInt.Text, out annualrate))
{
annualrate = annualrate / 100;
double monthlyrate = annualrate / 12;
double changerate = (1 + monthlyrate);
txtMonths.Text = months.ToString();
months++;
balance = monthlypmt + Math.Pow(changerate, months);
txtBalance.Text = balance.ToString("c");
balance++;
}
else
{
MessageBox.Show("Please insert valid interest rate.");
}
}
else
{
MessageBox.Show("Please insert valid number.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
My form:
P.S. Here is the updated code, and yes I have additional problems!
namespace Assignment1_BTM380
{
public partial class frmSavingsCalculator : Form
{
public frmSavingsCalculator()
{
InitializeComponent();
}
int months = 0;
double balance = 0;
private void btnNext_Click(object sender, EventArgs e)
{
double monthlypmt;
int annualrate;
if (double.TryParse(txtMonthlySavings.Text, out monthlypmt))
{
if (int.TryParse(txtAnnualInt.Text, out annualrate))
{
double realannualrate = (double) annualrate / 100;
double monthlyrate = realannualrate / 12;
double interest = (monthlypmt * monthlyrate);
txtMonths.Text = months.ToString();
months++;
balance = monthlypmt + balance * (Math.Pow(1+monthlyrate,months));
txtBalance.Text = balance.ToString("c");
}
else
{
MessageBox.Show("Please insert valid interest rate.");
}
}
else
{
MessageBox.Show("Please insert valid number.");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
SO, if you have the patience, bear with me. I managed to get the two text boxes to react each time I click the "Next Month" button, only I can't seem to get the appropriate values in the Balance. According to my professor's example, after 12 months, the Balance should display $619.86, only it shows $868.06 in my Form. I think the problem is with the Balance calculation, which I hope some of you can comment on.
Thanks to everyone who took the time to reply!
You're actually doing it right, the problem is that you're always getting the same result after the initial calculation due to a variable type problem.
The problem is the fact that the local variable "annualrate" is Integer.
Initially it makes sense since you are forcing them to write an integer number in the text box. Yet problem arises when you make it an actual rate by dividing it by 100.
annualrate = annualrate / 100;
Unless the rate in the text box is greater or equal to 100 you will always get a rate of zero because mathematically the result of any number between 0 and 100 (not including 100) divided by 100 is always between 0 and 1 (not including 1). For example, 50% rate should give you 0.5 but will result into just 0 because of the Integer division.
An easy fix will be:
...
double realannualrate = annualrate / 100;
double monthlyrate = realannualrate / 12;
...
You might also want to consider moving calculations and initialization to a separate functions
I have just programmed a very simple program to help me work out the amount of carbohydrate per meal (I have diabetes) and my issue is I get a System.FormatException when one of my textboxes are empty.
How may I prevent this please ?
My code (using a form consisting of 3 textboxes; 2 of which require input from me and a third which shows the result of a simple equation).
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form()
{
tbCCG.TextChanged += TextBoxChanged;
tbCTG.TextChanged += TextBoxChanged;
}
private void TextBoxChanged(object sender, EventArgs e)
{
decimal carbsT;
decimal carbsPerC = Convert.ToDecimal(tbCCG.Text);
decimal totCarbs = Convert.ToDecimal(tbCTG.Text);
carbsT = carbsPerC / 100 * totCarbs;
tbTC.Text = carbsT.ToString("###,###.00");
}
}
you can verify the text in your text boxes
if (string.IsNullOrWhiteSpace(tbCCG.Text))
tbCCG.Text = "0";
if (string.IsNullOrWhiteSpace(tbCTG.Text))
tbCTG.Text = "0";
decimal carbsPerC = Convert.ToDecimal(tbCCG.Text);
decimal totCarbs = Convert.ToDecimal(tbCTG.Text);
but if you don't have any kind of restrictions on your text box try using decimal.TryParse.
private void txtrate_TextChanged(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtqty.Text);
int b = Convert.ToInt32(txtrate.Text);
int c = a * b;
txttotal.Text = Convert.ToString(c);
//txttotal.Text = (Convert.ToInt32(txtqty.Text) * Convert.ToInt32(txtrate.Text)).ToString();
}
Well... this error occurs of txtqty.Text (or txtrate.Text for variable b) does not contain a valid number. So the user entered letters or other characters instead of 0 till 9.
You could try to validate your input first with TryParse:
private void txtrate_TextChanged(object sender, EventArgs e)
{
int a = Convert.ToInt32(txtqty.Text);
int b = Convert.ToInt32(txtrate.Text);
if (Int32.TryParse(txtqty.Text, out a) && (Int32.TryParse(txtrate.Text, out b)
{
int c = a * b;
txttotal.Text = c.ToString();
}
}
Yes, this is due to the value not contained only numbers, to avoid this situation, please setup the type of data you are trying to collect with the text fields, you can setup refer this post for a detailed walk through on how to do it.
Yes, I would suggest TryParsetoo :
private void txtrate_TextChanged(object sender, EventArgs e)
{
int number;
bool result = Int32.TryParse(txtqty.Text, out number);
if (result)
{
//Converting is Ok, proceed
}
else
{
//Convertign fail
txtqty.Focus();
MessageBox.Show("Please enter only number for this field");
return;
}
}
I would suggest making this for each textbox with setting the focus to the textbox with incorrect input and providing an useful message for the user. In my opinion this is a suitable and user-friendly way.
I have been given a coding assignment by my recruiter for a job as a junior developer. There were three choices and I went with a problem that requires calculating a purchase. All items are supposed be taxed 10% unless they are books, food or medicine. Anything imported is taxed an extra 5%, even if they are tax exempt. So I created a form that allows a user to type in the name of the item, two check boxes for whether they are imported or tax exempt, a textbox for inputing price, and a text box for each input. Underneath is a textbox that is supposed to calculate the total sales tax, underneath that is a textbox for the total. The first checkbox is named "Item1Import" the next one is called "Item1Exempt." The price text box is named "Item1Price" and the other "Item1Output." And for each item the number would change, Item2Import, Item3Import, etc. The last two textboxes are called "SalesTax" and "Total."
Here is the code I have so far.
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;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Item1Price_TextChanged(object sender, EventArgs e)
{
if(Item1Exempt.Checked && Item1Import.Checked)
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text)) + (Convert.ToInt32(Item1Price.Text) * 0.05).ToString("C2"));
}
else if(Item1Exempt.Checked && !Item1Import.Checked)
{
Item1Output.Text = (Convert.ToInt32(Item1Price.Text)).ToString("C2");
}
else if(!Item1Exempt.Checked && Item1Import.Checked)
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text) + (Convert.ToInt32(Item1Price.Text) * 0.1) + (Convert.ToInt32(Item1Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text)) + (Convert.ToInt32(Item1Price.Text) * 0.1)).ToString("C2");
}
}
private void Item2Price_TextChanged(object sender, EventArgs e)
{
if (Item2Exempt.Checked && Item2Import.Checked)
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text)) + (Convert.ToInt32(Item2Price.Text) * 0.05).ToString("C2"));
}
else if (Item2Exempt.Checked && !Item2Import.Checked)
{
Item2Output.Text = (Convert.ToInt32(Item2Price.Text)).ToString("C2");
}
else if (!Item2Exempt.Checked && Item2Import.Checked)
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text) + (Convert.ToInt32(Item2Price.Text) * 0.1) + (Convert.ToInt32(Item2Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text)) + (Convert.ToInt32(Item2Price.Text) * 0.1)).ToString("C2");
}
}
private void Item3Price_TextChanged(object sender, EventArgs e)
{
if (Item3Exempt.Checked && Item3Import.Checked)
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text)) + (Convert.ToInt32(Item3Price.Text) * 0.05).ToString("C2"));
}
else if (Item3Exempt.Checked && !Item3Import.Checked)
{
Item3Output.Text = (Convert.ToInt32(Item3Price.Text)).ToString("C2");
}
else if (!Item3Exempt.Checked && Item3Import.Checked)
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text) + (Convert.ToInt32(Item3Price.Text) * 0.1) + (Convert.ToInt32(Item3Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text)) + (Convert.ToInt32(Item3Price.Text) * 0.1)).ToString("C2");
}
}
private void Item4Price_TextChanged(object sender, EventArgs e)
{
if (Item4Exempt.Checked && Item4Import.Checked)
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text)) + (Convert.ToInt32(Item4Price.Text) * 0.05).ToString("C2"));
}
else if (Item4Exempt.Checked && !Item4Import.Checked)
{
Item4Output.Text = (Convert.ToInt32(Item4Price.Text)).ToString("C2");
}
else if (!Item4Exempt.Checked && Item4Import.Checked)
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text) + (Convert.ToInt32(Item4Price.Text) * 0.1) + (Convert.ToInt32(Item4Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text)) + (Convert.ToInt32(Item4Price.Text) * 0.1)).ToString("C2");
}
}
private void SalesTax_TextChanged(object sender, EventArgs e)
{
SalesTax.Text = (((Convert.ToInt32(Item1Output.Text) - Convert.ToInt32(Item1Price.Text)) + ((Convert.ToInt32(Item2Output.Text) - Convert.ToInt32(Item2Price.Text)) + ((Convert.ToInt32(Item3Output.Text) - Convert.ToInt32(Item3Price.Text)) + ((Convert.ToInt32(Item4Output.Text) - Convert.ToInt32(Item4Price.Text)).ToString("C2"));
}
private void Total_TextChanged(object sender, EventArgs e)
{
Total.Text = ((Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)).ToString("C2"));
}
}
}
The first problem I'm having is whenever I do type into Item1Price, it outputs to Item1Output but it doesn't work with the others, and the "salestax" and "total" textboxes don't show anything either.
The second problem is I can't type a number like "O.OO" but I can do "00" and whenever I delete the number, it crashes.
Any help would be really appreciated. Thank you in advance.
First thing its not in good fashion to post coding assignment in a forum to get help with for a job. If you cant complete the coding assignment by yourself I would suggest you reevaluate your skills and ask yourself if your ready for the position that you're trying to obtain. With that said I remember the days in my beginning when I was going after those positions I probably had no business being in at the time so I can sympathize with that. Now to your code.
First of all, you need to surround your conversions in a try catch block, the reason your application is crashing is because 0.00 will not convert into a integer since there is a decimal there. 00 will work but when you delete them your textbox.text value is now nothing which is not going to convert either and your program will crash. So you will need to add logic to handle an empty string value and not do a conversion. I would suggest you use decimal datatype when dealing with money values. As suggested also I would create a method in which you could pass the check box values and return a string value back to set your textbox values. This could clean up your event handler code cause it seems your calculations are the same.