How do I add calculations to my GUI in C#? - c#

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.

Related

Return get set method value to label

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.

My code is reading the textbox just once

The problem is that my code is just reading the Textboxes just the very first time, wheneaver I do any change to the Textboxes it doesn`t read the new ones.
This is the code of the form with 2 textBoxes.
public partial class Form1 : Form
{
double tb1, tb2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 forming = new Form1();
Reading objR = new Reading(forming);
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
}
And the class where I´m trying to read the textboxes is this:
class Reading
{
double _tb1, _tb2;
public Reading(Form1 form)
{
this._tb1 = double.Parse(form.textBox1.Text);
this._tb2 = double.Parse(form.textBox2.Text);
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}
I think that Reading objR = new Reading(forming);reads the TextBoxes but they are read just once, When I Click my Button again it is just giving me the same info, I added the method mAdd to make sure the textboxes are being used correctly.
What can I do to actualy read the newest data in the Textboxes?
First, it's overkill to pass the entire form in to your Reading class' constructor. Why not just have a constructor with two double arguments?
Second, if you have to pass the form, then remove the Form1 forming = new Form1(); and replace the next line with Reading objR = new Reading(this);
The main reason is you are passing a NEW instance of Form1 to your reading class and not the instance where the textboxes you are changing.
Just to add to ffa's answer.
With this, the return value of reading class' mAdd and mAdd2 will be the same.
private void button1_Click(object sender, EventArgs e)
{
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
Reading objR = new Reading(tb1, tb2);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
class Reading
{
double _tb1, _tb2;
public Reading(string tb1, string tb2)
{
this._tb1 = double.Parse(tb1);
this._tb2 = double.Parse(tb2);
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}
public partial class Form1 : Form
{
double tb1, tb2;
private void button1_Click(object sender, EventArgs e)
{
Reading objR = new Reading();
tb1 = double.Parse(textBox1.Text);
tb2 = double.Parse(textBox2.Text);
textBox4.Text= objR.mAdd(tb1,tb2).ToString();
textBox5.Text = objR.mAdd2().ToString();
}
public class Reading
{
public double Reading(double a,double b)
{
_tb1= a;
_tb2 = b;
}
public double mAdd(double a, double b)
{
return a + b;
}
public double mAdd2()
{
return _tb1 + _tb2;
}
}

"cannot assign because part of method group" [closed]

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

Need to use created class to create an instance and use it in a Form.cs file

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);

Want to avoid default zero value

I have the a class in my application. It has been bound to winform textbox controls. But the textbox which is bound to BookingNo property, always shows zero (0). But i want the textbox keep empty. Is there any way to do it? Here is my code snippet.
public class Booking
{
private int pBookingNo;
private string pCustomerName;
private string pAddress;
public int BookingNo
{
get { return pBookingNo; }
set
{
if (!value.Equals(pBookingNo))
{
pBookingNo = value;
}
}
}
public string CustomerName
{
get { return pCustomerName; }
set
{
if (!value.Equals(pCustomerName))
{
pCustomerName = value;
}
}
}
public Booking() { }
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
AddDataBindings();
}
private void AddDataBindings()
{
bsBooking.DataSource = typeof(Booking);
txtBookingNo.DataBindings.Add("Text", bsBooking, "BookingNo", true, DataSourceUpdateMode.OnPropertyChanged, null, "G", GlobalVariables.CurrentCultureInfo);
txtCustomerName.DataBindings.Add("Text", bsBooking, "CustomerName");
}
}
The default value of an Integer is 0, so you have to wrap it into some other object, which supports values other than 0, like
public int? BookingNo { get; set; }
You can use Nullable Type
public int? pBookingNo
{
get;
set;
}
Link : http://msdn.microsoft.com/fr-fr/library/1t3y8s4s(v=vs.80).aspx
You could use custom formatting for the binding by adding a handler to the Format event (http://msdn.microsoft.com/en-us/library/system.windows.forms.binding.format.aspx) and return an empty string when the value is zero. But you wouldn't be able to tell whether the value is actually zero or it just hasn't been set already, in which case using the int? approach suggested by #Grumbler85 is better.
what´s about:
textBox1.BindingContextChanged += new EventHandler(BindingContext_Changed);
private void BindingContext_Changed(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
if (txtBox.Text == "0"){
txtBox.Text = "";
}
}
don´t know if it works, just an idea.

Categories

Resources