Return get set method value to label - c#

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.

Related

Adding list from controller class to a form list box

Hi there I have a problem that I am currently stuck with. I'm trying to get myA list to show in my list box in my managing accounts from but when I run the program nothing shows up in the list box.
Here is my controller class, it hold a method to MakeAccounts() and AddAccounts()
// Methods for handling accounts
public void MakeAccounts()
{
myA.Add(new Account.Everyday());
myA.Add(new Account.Investment(5, 10));
myA.Add(new Account.Omni(5, 10, -100));
myA[0].Balance = 50;
myA[1].Balance = 500;
myA[2].Balance = 5000;
// WriteBinaryData();
}
Here is my Manage Accounts From class, it has a DisplayAccounts() method which I have called in the Initialize Component part.
private void DisplayAccounts()
{
listBoxManageAccounts.Items.Clear();
foreach (Account account in control.myA)
{
listBoxManageAccounts.Items.Add(account);
}
if (listBoxManageAccounts.Items.Count >= 1)
{
listBoxManageAccounts.SelectedIndex = 0;
}
}
Here is my account class:
public class Account
{
static int nextAccountID = 1;
protected int accountID;
protected string typeName;
protected decimal balance;
protected string lastTransaction;
public Account()
{
accountID = nextAccountID;
nextAccountID++;
balance = 0;
lastTransaction = "There are no transactions.";
}
public decimal Balance
{
get { return balance; }
set { balance = value; }
}
// public int Interest
// {
// set { Interest = 4; }
// }
public class Everyday : Account
{
public Everyday()
{
typeName = "Everyday";
}
}
public class Investment : Account
{
protected decimal interestRate;
protected decimal failedTransFee;
public Investment(decimal newInterestRate, decimal newFailedTransFee)
{
typeName = "Investment";
interestRate = newInterestRate;
failedTransFee = newFailedTransFee;
}
}
public class Omni : Account
{
protected decimal interestRate;
protected decimal failedTransFee;
protected decimal overdraftLimit;
public Omni(decimal newInterestRate, decimal newFailedTransFee, decimal newOverdraftLimit)
{
typeName = "Omni";
interestRate = newInterestRate;
failedTransFee = newFailedTransFee;
overdraftLimit = newOverdraftLimit;
}
}
}
So what I want to happen is when this form is opened up I want the accounts (everyday, investment, omni) to appear in the list box straight away. Currently when I open this form nothing happens. Can anyone please tell me what's happening or where I have gone wrong?

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

Employee and ProductionWorker Classes, getting info from classes

I'm not completely sure the title was good for this. I'm stuck on an assignment for school there is suppose to be a video to shows how to do this but for the life of me I can't figure out how to download the student files from the pearson website. The following is the problem I'm working on.
Employee and ProductionWorker Classes
Create an Employee class that has properties for the following data:
Employee name
Employee number
Next, create a class named ProductionWorker that is derived from the Employee class. The ProudctionWorker class should have properties to hold the following data:
Shift number (an integer, such as 1, 2, or 3)
Hourly pay rate
The workday is divided into two shifts: day and night. The Shift property will hold an integer value representing the shift that the employee works. The day shift is shift 1 and the night shift is shift 2.
Create an application that creates an object of the ProductionWorker class and lets the user enter data for each of the object's properties. Retrieve the object's properties and display their values.
Here is the code I working on for it:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace classes
{
public partial class frmMainClasses : Form
{
string EmpShift = "";
string EmployeeName = "";
int EmployeeNumber = 0;
float HourlyPayRate = 0;
public class Employee
{
public string EmployeeName { get; set; }
public int EmployeeNumber { get; set; }
}
public class ProductionWorker : Employee
{
public float HourlyPayRate { get; set; }
public Shift Shift { get; set; }
}
public enum Shift
{
Day = 1,
Night = 2
}
public frmMainClasses()
{
InitializeComponent();
}
private void btxExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnGetInfo_Click(object sender, EventArgs e)
{
string EmpShift = "";
ProductionWorker productionWorker = new ProductionWorker();
productionWorker.EmployeeName = txtName.ToString();
EmployeeName = productionWorker.EmployeeName; //Added mostly because I couldn't get EmployeeName to show anything in the messagebox
productionWorker.EmployeeNumber = Convert.ToInt32(txtIdNumb.text);
productionWorker.HourlyPayRate = Convert.ToInt32(txtPay.text);
EmpShift = Convert.ToString(txtShift.text);
txtName.Text = "";
txtIdNumb.Text = "";
txtPay.Text = "";
txtShift.Text = "";
}
private void btnShow_Click(object sender, EventArgs e)
{
MessageBox.Show("Name " + EmployeeName + "IDNumber " + EmployeeNumber + "Hourly rate " + txtPay + "Shift " + txtShift);
}
}
}
The code itself isn't showing any errors, but when I try to run it I get:
The string EmpShift thing is in there because I couldn't figure out how to work with the shift code more or less am using that as a place holder until I finger it out. I have no idea how to fix the problem, hopefully its a little mistake.
Thanks to help from the commets I was able to fix the first problem I had, now I'm having a problem with the message box at the end. The information I put into it is, Glitter for name, 12 for ID number, 1 for shift, and 12 for pay. Here's what its showing:
Name System.Windows.Forms.TextBox, Text: GlitterIDNumber 0Hourly rate
System.Windows.Forms.TextBox, Text: Shift SystemWindowsForm.TextBox, Text:
Convert.ToString doesnt give you an error because one of it calls its overload with object - public static string ToString(object value). However, since you are interested in user entered value, please use - TextBox.Text property instead of passing the TextBox.
Update 1 : some insides about this behavior
System.Convert.ToString(object value) is implemented as follows in .net -
public static string ToString(Object value, IFormatProvider provider) {
IConvertible ic = value as IConvertible;
if (ic != null)
return ic.ToString(provider);
IFormattable formattable = value as IFormattable;
if (formattable != null)
return formattable.ToString(null, provider);
return value == null? String.Empty: value.ToString();
}
therefore it ends up calling TextBox.ToString()
and System.Convert.ToInt32(object value) is as follows
public static int ToInt32(object value) {
return value == null? 0: ((IConvertible)value).ToInt32(null);
}
therefore an invalid cast exception because of this - ((IConvertible)value).ToInt32(null)
Update 2 : Code refactored for it to work
public partial class frmMainClasses : Form
{
//Change 1
//I have removed all class level string since they tend to make your code complicated & difficult to manage
//I'll replace all of them this a single instance of ProductionWorker class, a single object is easy to manage than a bunch
ProductionWorker productionWorker = new ProductionWorker(); // Creating the production Worker at class level
public class Employee
{
public string EmployeeName { get; set; }
public int EmployeeNumber { get; set; }
}
public class ProductionWorker : Employee
{
public float HourlyPayRate { get; set; }
public Shift Shift { get; set; }
}
public enum Shift
{
Day = 1,
Night = 2
}
public frmMainClasses()
{
InitializeComponent();
}
private void btxExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnGetInfo_Click(object sender, EventArgs e)
{
//Change 2 : set the values of the class level variable
productionWorker.EmployeeName = txtName.Text; //.ToString(); // Change 3 removing the .ToString();
productionWorker.EmployeeNumber = Convert.ToInt32(txtIdNumb.Text);
productionWorker.HourlyPayRate = Convert.ToInt32(txtPay.Text);
productionWorker.Shift = (Shift)Enum.Parse(typeof(Shift), txtShift.Text);
//change 4 : using .ResetText() instead of Text
txtName.ResetText();// .Text = "";
txtIdNumb.ResetText();//.Text = "";
txtPay.ResetText();//.Text = "";
txtShift.ResetText();//.Text = "";
}
private void btnShow_Click(object sender, EventArgs e)
{
// change 5 : accessing class level productionWorker instead of bunch of strings
MessageBox.Show("Name " + productionWorker.EmployeeName + " IDNumber " + productionWorker.EmployeeNumber + " Hourly rate " + productionWorker.HourlyPayRate + " Shift " + productionWorker.Shift);
}
}
I've added comments to elaborate what all changes I've made, please write me a comment if you have any questions.
Also, at the moment your code does not validate user inputs in text boxes.

How do I add calculations to my GUI in 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.

Categories

Resources