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();
Related
I have a comboBox where the user can select from a variety of drinks
comboBoxBeverage.Items.Add("");
comboBoxBeverage.Items.Add("Soda $1.95");
comboBoxBeverage.Items.Add("Tea $1.50");
comboBoxBeverage.Items.Add("Coffee $1.25");
comboBoxBeverage.Items.Add("Mineral Water $2.95");
comboBoxBeverage.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxBeverage.SelectedIndex = 0;
but I want to take the option selected in the combobox and split it so I can use the price.
I tried doing
double beverage;
beverage = double.Parse(comboBoxBeverage.Text.TrimStart(new[] { '$' }));
labelSubtotal.Text = beverage.ToString();
but it's giving me an error:
System.FormatException: 'Input string was not in a correct format.'
A more OOP approach to your question and also removing the problem of parsing the input text is the following:
First create a class Beverage
public class Beverage
{
public string Description {get;set;}
public decimal Price {get;set;}
public override string ToString()
{
return $"{this.Description} {(this.Price != 0 ? this.Price.ToString("C") : "")}";
}
}
now create a List<Beverage> with your data
List<Beverage> drinks = new List<Beverage>()
{
new Beverage {Description = "", Price = 0m},
new Beverage {Description = "Soda", Price = 1.95m},
new Beverage {Description = "Tea", Price = 1.50m},
new Beverage {Description = "Coffee", Price = 1.25m},
new Beverage {Description = "Mineral Water", Price = 2.95m}
};
comboBoxBeverage.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxBeverage.DataSource = drinks;
Now you can retrieve a Beverage instance from your combobox instead of a string and you get the Price directly from this Beverage instance
private void Button1_Click(object sender, EventArgs e)
{
if(comboBoxBeverage.SelectedItem != null)
{
Beverage b = comboBoxBeverage.SelectedItem as Beverage;
SubTotal += b.Price;
labelSubtotal.Text = SubTotal.ToString("C");
}
}
This solution works because the ComboBox calls ToString() for every item added to its list through the DataSource property unless you set the DisplayMember and ValueMember properties.
Also notice that when dealing with currency values you should use the decimal type, not the double type
You might give this a shot. It just takes the selected item, splits it into two elements where the $ is located, skips over the first element and assigns the second element's value to itemPrice:
using System;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public double SubTotal { get; set; }
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
comboBoxBeverage.Items.Add("");
comboBoxBeverage.Items.Add("Soda $1.95");
comboBoxBeverage.Items.Add("Tea $1.50");
comboBoxBeverage.Items.Add("Coffee $1.25");
comboBoxBeverage.Items.Add("Mineral Water $2.95");
comboBoxBeverage.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxBeverage.SelectedIndex = 0;
}
private void Button1_Click(object sender, EventArgs e)
{
var itemPrice = comboBoxBeverage.Text.Split('$').Skip(1).FirstOrDefault();
SubTotal += double.Parse(itemPrice);
labelSubtotal.Text = "$" + SubTotal;
}
}
}
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.
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
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.
I feel like I'm missing something obvious here. This is a screenshot of my form.
I have two classes, ShoppingBasket and OrderItem, and then the Form1 class. I have four properties in OrderItem that I want to use in ShoppingBasket. I want to take the product name in textbox1, the quantity in numericupdown1, and the latest price in textbox2, then I will click the add button which will validate the values using the OrderItem class, then put them into the AddProduct method in the ShoppingBasket class which will hopefully add a line to the listbox in the form.
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
decimal latestPrice;
ShoppingBasket addButtonShoppingBasket = new ShoppingBasket();
decimal.TryParse(textBox2.Text, out latestPrice);
OrderItem currentItemQuantity1 = new OrderItem(textBox1.Text, latestPrice, Convert.ToInt32(numericUpDown1.Value));
addButtonShoppingBasket.AddProduct(currentItemQuantity1.ProductName, currentItemQuantity1.LatestPrice, currentItemQuantity1.Quantity);
}
}
ShoppingBasket:
public class ShoppingBasket
{
public ShoppingBasket()
{
}
public void AddProduct(string productName, decimal latestProductValue, int quantity)
{
Form1 newform = new Form1();
string itemFormatString = "{0,-50}{1,0}{2,50}";
newform.listBox1.Items.Add(string.Format(itemFormatString, productName, Convert.ToString(quantity), Convert.ToString(latestProductValue)));
}
}
OrderItem:
public class OrderItem
{
public OrderItem(string productName, decimal latestPrice, int quantity)
{
ProductName = productName;
LatestPrice = latestPrice;
Quantity = quantity;
TotalOrder = latestPrice * quantity;
}
public string ProductName { get; set; }
public decimal LatestPrice { get; set; }
public int Quantity { get; set; }
public decimal TotalOrder { get; set; }
}
Your problem is, that you are creating a new form from your ShoppingBasked, whenever a product is added:
public void AddProduct(string productName, decimal latestProductValue, int quantity)
{
Form1 newform = new Form1();
string itemFormatString = "{0,-50}{1,0}{2,50}";
newform.listBox1.Items.Add(string.Format(itemFormatString, productName, Convert.ToString(quantity), Convert.ToString(latestProductValue)));
}
newform is not the form that actually called AddProduct! Even if you do not see this newform anywhere (because newform.Show() isn't called), the list item get's added to this "invisible" form, not the original one.
To solve this problem, I suggest passing your form as parameter to AddProduct:
public void AddProduct(Form1 form, string productName, decimal latestProductValue, int quantity)
{
string itemFormatString = "{0,-50}{1,0}{2,50}";
form.listBox1.Items.Add(string.Format(itemFormatString, productName, Convert.ToString(quantity), Convert.ToString(latestProductValue)));
}
And call it like this:
private void addButton_Click(object sender, EventArgs e)
{
// ...
// Your current code here
// ...
addButtonShoppingBasket.AddProduct(this,
currentItemQuantity1.ProductName,
currentItemQuantity1.LatestPrice,
currentItemQuantity1.Quantity);
}
Also an general advice to continue is changing your design. At the moment, ShoppingBasket is highly coupled to Form1 - this means, you cannot add new items to your shopping basket from any other source than a Form1! But ShoppingBasket should not care about the source of the item it receives. Also at the moment you create a new ShoppingBasket, each time you insert an item. This means, you can only have one item per ShoppingBasket. So for further learning, I suggest following those points:
Make ShoppingBasket a member variable of Form1.
When adding items, add the item to this member variable.
Do not pass your form to AddProduct, instead make your ShoppingBasket provide information about the items it contains.
Call listBox1.Items.Add right after AddProduct.
Then your ShoppingBasket does not care about how your products are presented, it only cares about how the products are stored internally.