Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a form with the following code :
public partial class frmSalesTax : Form
{
public frmSalesTax()
{
InitializeComponent();
}
//declare variables
decimal ItemPrice = 00.00m;
decimal TaxAmount = 00.08m;
decimal TotalAmount = 00.00m;
private void btnCalc_Click(object sender, EventArgs e)
{
try
{
if (decimal.TryParse(txtItemPrice.Text, out ItemPrice))
{
//Instantiated instance of a class here.
CTransaction Calc;
Calc = new CTransaction();
//set properties to calc tax amount.
Calc.SalesTaxRate = .08m;
Calc.TxtItemPrice = ItemPrice;
//call the method in the instance of the class
TaxAmount = Calc.CalculateTax();
//Set tax amount property to be available for the calc.
Calc.CalculateTax = TaxAmount;
//call the method in the instance of the class.
TotalAmount = Calc.CalculateTotal();
//Display the values
lblTaxAmt.Text = TaxAmount.ToString("c");
lblTotal.Text = TotalAmount.ToString("c");
}
else
{
MessageBox.Show("Enter a numeric value please");
txtItemPrice.Focus();
txtItemPrice.SelectAll();
lblTaxAmt.Text = string.Empty;
lblEndTotal.Text = string.Empty;
}
}
catch
{
MessageBox.Show("Critical Error");
}
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
}
and a class :
public class CTransaction
{
//Create private fields
private decimal salesTaxRate = .07m;
private decimal ItemPrice;
private decimal taxAmount;
//Define the properties
public decimal SalesTaxRate
{
get { return salesTaxRate;}
set { salesTaxRate = value;}
}
public decimal TxtItemPrice
{
get { return ItemPrice; }
set { ItemPrice = value;}
}
//Custom methods
public decimal CalculateTax()
{
return ItemPrice * SalesTaxRate;
}
public decimal CalculateTotal()
{
return ItemPrice + taxAmount;
}
}
Im getting the "cannot assign to 'CalculateTax' because it is a method group. (Form1.cs .. line 54 .. column 21)
The form has the following fields on it for the user to interact with
txtItemPrice (textbox)
3 - buttons (calc, clear, exit)
lblTaxAmount (which should display how my tax is being applied to the item.
lblEndTOtal (which should be the itemPrice + TaxAmount
This is the problem line:
//Set tax amount property to be available for the calc.
Calc.CalculateTax = TaxAmount;
You are trying to assign a value (TaxAmount) to a method (CalculateTax). You can't do that. If you are trying to set the tax rate then you need to add a public property to allow it to be set:
Calc.TaxAmount = TaxAmount;
Then in your Calc class:
public decimal TaxAmount
{
get { return taxAmount; }
set { taxAmount = value; }
}
Then everything should work as you expect.
Your line Calc.CalculateTax is a method in order for you to pass a value through a method, you should pass it as a parameter.
In your code, i would make a change on the CTransaction Class:
public decimal CalculateTotal(decimal taxAmount)
{
return itemPrice + taxAmount;
}
And in your frmSalesTax, you just have to remove your line:
//Set tax amount property to be available for the calc.
Calc.CalculateTax = TaxAmount;
And then in your line , TotalAmount = Calc.CalculateTotal();, the taxAmount variable as a parameter for TotalAmount method. And it should be like that:
TotalAmount = Calc.CalculateTotal(taxAmount);
It just should work like you expect.
For more information check these links:
C# Methods
C# Passing Parameters
Related
I'm currently stuck on this for 2 hours and did everything I could to find answers but none yet!
public class Snack
{
public string snack { get; set; }
public double amount { get; set; }
public int price { get; set; }
public Snacks snacks;
public enum Snacks
{
friet,
kroket,
frikandel,
Burger,
}
}
In the load method, I'm initializing my ListView:
private void load()
{
lstSnacks.View = View.Details;
lstSnacks.Columns.Add("snack");
lstSnacks.Columns.Add("amount");
lstSnacks.Columns.Add("price");
cmbSnack.Items.AddRange(Enum.GetNames(typeof(Snack.Snacks)));
cmbSnack.SelectedIndex = (int)Snack.Snacks.friet;
}
After that, I have a button where I add some snacks with the amount entered in the textbox and a fixed price:
private void btnAdd_Click(object sender, EventArgs e)
{
if (!lstSnacks.Items.ContainsKey(cmbSnack.SelectedItem.ToString()))
{
double totalprice = 0;
Snack snack1 = new Snack();
snack1.snack = cmbSnack.SelectedItem.ToString(); ;
snack1.amount = Convert.ToDouble(txtAmount.Text);
ListViewItem item = lstSnacks.Items.Add(cmbSnack.SelectedItem.ToString());
item.SubItems.Add(snack1.amount.ToString());
if (cmbSnack.SelectedIndex == 0)
{
snack1.price = (int)(snack1.amount * 2.50);
item.SubItems.Add(snack1.price.ToString());
}
}
I need to look into my ListView and add a snack if it's not already there. If it is, it should tell you that it's already in there, but items.ContainsKey is not working for me properly. What am I doing wrong?
The line...
ListViewItem item = lstSnacks.Items.Add(cmbSnack.SelectedItem.ToString());
...sets the Text property of the ListViewItem. To be able to use ContainsKey(), you need to also set its Name property.
One more thing: Consider using double.TryParse() instead of Convert.ToDouble() because there's no guarantee that the user will enter a valid number. When dealing with user input, always favor the .TryParse() methods over Convert.ToXXXX() or .Parse().
I would change the code into something like this:
string itemName = cmbSnack.SelectedItem.ToString();
if (lstSnacks.Items.ContainsKey(itemName))
{
MessageBox.Show("The item already exists in the list.", "Duplicate item");
return;
}
if (!double.TryParse(txtAmount.Text, out double amount))
{
MessageBox.Show("Please enter a valid amount.", "Incorrect 'Amount' value");
return;
}
double totalprice = 0;
Snack snack1 = new Snack();
snack1.snack = itemName;
snack1.amount = amount;
ListViewItem item = lstSnacks.Items.Add(itemName);
item.Name = itemName;
item.SubItems.Add(snack1.amount.ToString());
if (cmbSnack.SelectedIndex == 0)
{
snack1.price = (int)(snack1.amount * 2.50);
item.SubItems.Add(snack1.price.ToString());
}
In my Windows form I have 2 text boxes namely, start odometer reading and end odometer reading. My goal is to subtract the "start reading" from the "end reading" and display the difference in the label next to the Name and phone number of the client in the windows form label.
How do I return the value of the method getMilesCharge() and display it on the confirmLabel?
Code for the Car Rental Class
//A class that represents the Rental Agency Class.
namespace Assignment1
{
partial class RentalAgencyClass
{
//instance variables
public string customerName { get; set; }
public string phoneNumber { get; set; }
public double sMiles { get; set; }
public double eMiles { get; set; }
public double noOfDays { get; set; }
private double DAY_CHARGE = 15;
private double MILE_CHARGE = 0.12;
//Constructor class
//sets the value of the starting and ending miles.
//sets the value of the number of days the car was rented for
public RentalAgencyClass(double startMiles, double endMiles, double days)
{
startMiles = sMiles;
endMiles = eMiles;
days = noOfDays;
}
//method to calculate the number of miles driven on the rental
public double getMileCharge()
{
double milesDriven = 0;
milesDriven = eMiles - sMiles;
return milesDriven * MILE_CHARGE;
}
//method to calculate the Day Charges on the rental
public double getDayCharge()
{
return noOfDays * DAY_CHARGE;
}
//Property to display the information on the label
public string GetInfo()
{
return customerName + " | " + phoneNumber + " | " + getDayCharge() +" miles";
}
}
}
Form Designer Class code
namespace Assignment1
{
public partial class RentalAgencyClass : Form
{
RentalAgencyClass aCarRental;
public RentalAgencyClass()
{
InitializeComponent();
}
private void calculateButton_Click(object sender, EventArgs e)
{
try
{
//instantiates object
aCarRental = new RentalAgencyClass();
aCarRental.customerName = nameTextBox.Text;
aCarRental.phoneNumber = phoneTextBox.Text;
//aCarRental. = getDayCharge();
// aCarRental.milesDriven = //store the difference in this variable
//displayLabel.Text = "(student information saved)";
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error");
}
//Displays information about the Rental
confirmLabel.Text = aCarRental.GetInfo();
}
}
}
By calling aCarRental = new RentalAgencyClass(); within your calculateButton_Click method you are calling the parameterless constructor of your partial class RentalAgencyClass, which means in your case, you are creating a new instance of your form instead of setting your properties. So sMiles and eMiles will stay by their default value 0.
To get your code working you have to do several steps.
At first I recommend you should split your form and your agency class.
So let's say, rename your form class to RentalCalculator. As a next step you have to/can remove the partial from your RentalAgencyClass, because it is not a part of your form class anymore and I assume you did not want to extend your class in another part of your code.
As LarsTech pointed out in the comments. You should now fix your RentalAgencyClass constructor to:
public RentalAgencyClass(double startMiles, double endMiles, double days)
{
this.sMiles = startMiles;
this.eMiles = endMiles;
this.noOfDays = days;
}
and may add the following property to your class
public double milesDriven
{
get
{
return this.eMiles - this.sMiles;
}
}
At least you have to change your event handler:
private void calculateButton_Click(object sender, EventArgs e)
{
try
{
// if not existing you have to create some input textboxes
double startMiles = Convert.ToDouble(startMilesTextBox.Text);
double endMiles = Convert.ToDouble(endMilesTextBox.Text);
double days = Convert.ToDouble(daysTextBox.Text);
// Hint: you are creating a new instance on every button click
// and overwriting your field in your form class.
aCarRental = new RentalAgencyClass(startMiles, endMiles, days);
aCarRental.customerName = nameTextBox.Text;
aCarRental.phoneNumber = phoneTextBox.Text;
// Store the result in local variables
// if you want to do something with them later
double dayCharge = aCarRental.getDayCharge();
double milesCharge = aCarRental.getMilesCharge();
double drivenMiles = aCarRental.milesDriven;
// displayLabel.Text = "(student information saved)";
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error");
}
//Displays information about the Rental
confirmLabel.Text = aCarRental.GetInfo();
}
Answering your question:
How do I return the value of the method getMilesCharge() and display it on the confirmLabel?
You will have to change the following line in your calculateButton_Click method from:
confirmLabel.Text = aCarRental.GetInfo();
to:
confirmLabel.Text = aCarRental.getMilesCharge().ToString();
Last but not least let me give you a kind advice.
You may take a look at the Microsoft Naming Guidelines.
For example: Properties should be named in PascalCasing.
But this is just my personal opinion.
this probably is very simple. This is an assignment for a class, there seems to be several versions of this floating around, and several versions of an answer but I'm not sure how they work. The assignment is to create two forms. One with a dorm price and meal price and the second form is to display the total price. I want the price to display into a input label on the price form. Except I'm not sure how to get the information from one to the other. Does this require me doing a get/set somewhere within my Calculator form?
This is form 1(Calculator) code:
public partial class Calculator : Form
{
Price myPrice = new Price();
decimal dorm = 0;
decimal meal = 0;
public Calculator()
{
InitializeComponent();
}
private void getPriceButton_Click(object sender, EventArgs e)
{
decimal price = 0;
getInput();
price = dorm + meal;
myPrice.ShowDialog();
}
private void getInput()
{
if(allenRadioButton.Checked)
{
dorm = 1500;
}
if(pikeRadioButton.Checked)
{
dorm = 1600;
}
if(farthingRadioButton.Checked)
{
dorm = 1800;
}
if(universityRadioButton.Checked)
{
dorm = 2500;
}
if(sevenRadioButton.Checked)
{
meal = 600;
}
if(fourteenRadioButton.Checked)
{
meal = 1200;
}
if(unlimitedRadioButton.Checked)
{
meal = 1700;
}
}
This is form2 (Price) code:
public partial class Price : Form
{
Calculator myCalulator = new Calculator();
public Price()
{
InitializeComponent();
}
priceLabel.Text = price.myCalculator.TosString("c");
}
you can make a variable of price in second form and pass your price to the constructor of Price form:
public string price;
public Price(string price)
{
this.price = price;
InitializeComponent();
}
private void getPriceButton_Click(object sender, EventArgs e)
{
decimal price = 0;
getInput();
price = dorm + meal;
Price myPrice = new Price(price)
myPrice.ShowDialog();
}
Pass the price as a parameter to a new parameterised constructor of the Price form and use this for further operations.
private decimal _price;
public Price(decimal pPrice)
{
InitializeComponent();
_price = pPrice;
...
}
Also instantiate the myPrice object in your button click event with this new constructor. like;
Price myPrice = new Price(price);
myPrice.ShowDialog();
For other ways to pass the value from one form to other, please refer to this link; How can I pass values from one form to another? and also Passing Parameters back and forth between forms in C#
You can Do this simply by adding a variable and making it public in the windows form like this.
public int PassValue
And pass a value to it, before the form is called
form1 obj = new form1();
obj.PassValue = 34;
obj.Show();
So, I'm at a loss here. Have a small project to work on. Have to create a trip class then create a Windows Form app and use the class I created to use the form to calculate miles per gallons used and Cost Per Mile.
Have completed the class:
namespace TripCalculator
{
class Trip
{
//Data members of class
private string destination;
private double distTrav;
private double totalCostGas;
private double numGallonsGas;
//Default Constructor
public Trip()
{
}
//Constructor with all parameters
public Trip(string tripDest, double milesTrav, double ttlPriceGas, n double numGalls)
{
destination = tripDest;
distTrav = milesTrav;
totalCostGas = ttlPriceGas;
numGallonsGas = numGalls;
}
//Propery for destination data field
public string Destination
{
set
{
destination = value;
}
get
{
return destination;
}
}
public double DistTrav
{
set
{
distTrav = value;
}
get
{
return distTrav;
}
}
public double TotalCostGas
{
set
{
totalCostGas = value;
}
get
{
return totalCostGas;
}
}
public double NumGallonsGas
{
set
{
numGallonsGas = value;
}
get
{
return numGallonsGas;
}
}
public double CalculateMPG()
{
return (distTrav / numGallonsGas);
}
public double CalculateCPM()
{
return (totalCostGas / numGallonsGas);
}
public override string ToString()
{
return CalculateMPG().ToString();
}
}
}
I want to be able to input destination, distance, cost, and gallons of gas into the form. Then I want the mpg and cost per mile to return to me in a textboxes.
Here's the form.cs
namespace TripCalculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calcBtn_Click(object sender, EventArgs e)
{
string destination;
double distTrav;
double totalCostGas;
double numGallonsGas;
destBox.Focus();
distBox.Focus();
gasBox.Focus();
galBox.Focus();
Trip aTrip = new Trip (destination, distTrav, totalCostGas, numGallonsGas );
mpgTxt.Text = aTrip.CalculateMPG().ToString();
cpmTxt.Text = aTrip.CalculateCPM().ToString();
destBox.Enabled = false;
}
}
}
Im getting 4 errors saying "Use of unassigned local variable 'destination' (As well as for the other 3 variables above). It'll start the program, but returns nothing when I type in the text boxes and click the button. What am I doing wrong? Please help! Thanks.
private void calcBtn_Click(object sender, EventArgs e)
{
string destination; // Give value for these
double distTrav; // Give value for these
double totalCostGas; // Give value for these
double numGallonsGas; // Give value for these
}
Assign some value, either from user input or hard coded value for testing
Something like the code below, where you get the values from the text box in your Winform assuming you have such text boxes.
string destination = DestinationTextBox.Text;
double distTrav = double.Parse(DistTravTextBox.Text);
double totalCostGas = double.Parse(TotalCostGasTextBox.Text);
double numGallonsGas = double.Parse(NumGallonsGasTextBox.Text);
You need to set the textbox values for the variables
string destination = txtDestination.Text;
double distTrav = double.Parse(txtTrav.Text);
double totalCostGas = double.Parse(txtCostGas.Text);
double numGallonsGas = double.Parse(GallonsGas.Text);
This is my first time using Windows Forms on Visual Studio with C#. I am trying to make my form have a button where when you click "Calculate Amount Due" that it will put what was calculated into the "Amount Due" field. But, anytime I say "textBox3 = aOrder.AmountDue()", it says it can not convert double to System.Windows.Forms.TextBox. How do I convert this appropriately? Here is my code for the program.
namespace MidTermPizzas
{
class pizzaOrder
{
public int numberOfCokes
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public int numberOfPizzas
{
get
{
throw new System.NotImplementedException();
}
set
{
}
}
public double InputOrder()
{
const double COKE_PRICE = 1.49;
const double PIZZA_PRICE = 7.99;
double inputOrder = (numberOfCokes * COKE_PRICE) + (numberOfPizzas * PIZZA_PRICE);
return InputOrder();
}
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return TaxDue();
}
public double GetAmountDue()
{
double getAmountDue = this.InputOrder() + this.TaxDue();
return GetAmountDue();
}
public double GetAmountPaid()
{
double getAmountPaid;
return GetAmountPaid();
}
public double GetChargeDue()
{
double getChargeDue = this.GetAmountDue() - this.GetAmountPaid();
return GetAmountPaid();
}
}
}
namespace MidTermPizzas
{
public partial class Form1 : Form
{
pizzaOrder aOrder = new pizzaOrder();
DailySummary aSummary = new DailySummary();
public Form1()
{
InitializeComponent();
}
//click File, Exit
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Enjoy your pizza!");
this.Close();
}
//click View, All Orders Placed
private void allOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
AllOrdersPlaced myForm = new AllOrdersPlaced();
myForm.Show();
}
//click View, Summary of Orders Placed
private void summaryOfOrdersToolStripMenuItem_Click(object sender, EventArgs e)
{
SummaryOfOrdersPlaced myForm2 = new SummaryOfOrdersPlaced();
myForm2.Show();
}
//text in box to the right of "Amount Due"
private void textBox3_TextChanged_1(object sender, EventArgs e)
{
textBox3 = aOrder.GetAmountDue();
}
}
}
textBox3.Text = Convert.ToString(aOrder.AmountDue());
Assuming AmountDue() is returning a Double.
You had two problems, you were trying to set the actual textbox object to a string instead of the .Text property of the textbox, and you aren't converting the double to a string.
textBox3 is the object. The object has various methods (to do stuff) and properties (to hold stuff), specifically textBox3.Text which is where you can set the text in the box. Remember MSDN is your friend.
To avoid this error, it's necessary assign the value Order.GetAmountDue() for Text property. This property contains the value of TextBox:
textBox3.Text = aOrder.GetAmountDue();
Because it's necessary keep the compatibility between the types, so you can't assign a Double for a TextBox, but you can assign a Double to a string (in this case the Text property its a string).
Maybe you need format the value, for more information see this link:
Double.ToString
In addition to the Textbox issue, I also don't think you should be returning the public method itself.ie
instead of
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return TaxDue();
}
You should have
public double TaxDue()
{
const double TAX = .073;
double taxDue = (this.InputOrder() * TAX);
return taxDue;
}
The first implementation doesn't make sense.