private void submitbutton_Click(object sender, EventArgs e)
{
if (fishingrodcomboBox.SelectedIndex == 2)
{
fishingrodcomboBox.SelectedIndex = 2;
decimal two = 18m;
decimal price = two * fishingrodnumericUpDown.Value;
totalfishingrodtextBox.Text = price.ToString("C");
}
else
{
//Do something
}
}
Textbox doesnt display the amount and how i do code it such that when i select something from the combo box i can each a different value?
Related
I have a GUI that is using a text field for a user int input.
a combo box that has drop downs for calculations (sum, add, div, mult. etc.)
then I click a button to calculate.
the Results show in bottom text field.
I am having trouble getting the combobox to string, so that I can make the right calculation.
The first part also needs the combobox to be selected on "Initialize" to add the value to the result text field. After that is added, all combobox choices after will utilize the initialized value in the results field and the user input field for any function calls.
namespace GUI
{
public partial class Form1 : Form
{
static void Main()
{
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string path = #"C:\Users\calculations.txt";
StreamReader sr = new StreamReader(path);
string x = sr.ReadToEnd();
string[] y = x.Split('\n');
for (int i = 0; i < y.Length; i++)
{
comboBox1.Items.Add(y[i]);
}
}
//Button to calculate Resualt
private void button1_Click(object sender, EventArgs e)
{
string x = comboBox1.SelectedItem.ToString();
int b = int.Parse(textBox2.Text);
if(x == "Initialize")
textBox1.Text = (b).ToString();
else if (textBox1 == null)
Console.WriteLine("Please Initialize value");
if(x == "Sum")
textBox1.Text = (b + b).ToString();
}
//Result text box
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
//User number input box
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
}
}
Values in calculation.txt
Initialize
Sum
Subtract
Product
Power
Log
I have been trying to get my amortization calculator to work however the ending payment balance does not end on 0 and my code does not output the correct values and I am stuck after doing some googling for a couple hours. I believe my issue is underneath the comment "Listbox Loop." Any help would be appreciated.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
// Allows for the hotkeys to be used even when out of focus from main form
this.KeyPreview = true;
}
private void MainForm_KeyPress(object sender, KeyPressEventArgs e)
{
// Adds hotkeys; Enter = Calculate, Escape = Exit
if (e.KeyChar == (char)Keys.Enter)
{
calculateButton.PerformClick();
}
else if (e.KeyChar == (char)Keys.Escape)
{
exitButton.PerformClick();
}
}
private void rebateCheck_CheckedChanged(object sender, EventArgs e)
{
// Enables & Disables rebate textbox based on rebate checkbox
if (rebateCheck.Checked == true)
{
rebateBox.Enabled = true;
}
else
{
rebateBox.Clear();
rebateBox.Enabled = false;
}
}
/* Selects data inside of the textbox when tabbing or clicking into it */
private void loanAmountBox_Enter(object sender, EventArgs e)
{
loanAmountBox.SelectAll();
}
private void loanAmountBox_Click(object sender, EventArgs e)
{
loanAmountBox.SelectAll();
}
private void annualAPRBox_Enter(object sender, EventArgs e)
{
annualAPRBox.SelectAll();
}
private void annualAPRBox_Click(object sender, EventArgs e)
{
annualAPRBox.SelectAll();
}
private void rebateBox_Enter(object sender, EventArgs e)
{
rebateBox.SelectAll();
}
private void rebateBox_Click(object sender, EventArgs e)
{
rebateBox.SelectAll();
}
/* Clears the list box when text is changed on any of the input boxes */
private void loanAmountBox_TextChanged(object sender, EventArgs e)
{
loanListBox.Items.Clear();
}
private void annualAPRBox_TextChanged(object sender, EventArgs e)
{
loanListBox.Items.Clear();
}
private void rebateBox_TextChanged(object sender, EventArgs e)
{
loanListBox.Items.Clear();
}
/* Only allows digits, periods, and control keys to be entered into textboxes */
private void loanAmountBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
return;
}
}
private void annualAPRBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
return;
}
}
private void rebateBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !Char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
return;
}
}
private void exitButton_Click(object sender, EventArgs e)
{
// Asks the user if they are sure they want to exit
DialogResult dialog = MessageBox.Show("Are you sure you want to exit?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); ;
if (dialog == DialogResult.Yes)
this.Close();
}
private void calculateButton_Click(object sender, EventArgs e)
{
// Declaring all variables
int monthsCounter;
double loan;
double rate;
double rebate;
double principal;
double balance;
int months = 0;
double principalPayment = 0;
double pmt = 0;
double interest = 0;
double totalInterest = 0;
double totalPrincipal = 0;
double totalPayment = 0;
double monthlyRate;
try
{
// Parse data from textboxes
double.TryParse(loanAmountBox.Text, out loan);
double.TryParse(annualAPRBox.Text, out rate);
double.TryParse(rebateBox.Text, out rebate);
// Check which loan month radio button is selected
if (loan6Months.Checked)
{
months = 6;
}
else if (loan12Months.Checked)
{
months = 12;
}
else if (loan18Months.Checked)
{
months = 18;
}
else if (loans24Months.Checked)
months = 24;
// Validates if the Loan Amount textbox is blank and if so, throws an error message pop up
if (loan == 0)
{
MessageBox.Show("Please enter a loan value.", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
loanAmountBox.Focus();
loanAmountBox.SelectAll();
}
else if (rate == 0)
{
MessageBox.Show("Please enter/select an APR value.", "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
annualAPRBox.Focus();
annualAPRBox.SelectAll();
}
rate = (rate / 100) / 12;
loan = loan - rebate;
// Listbox loop
for (monthsCounter = 1; monthsCounter <= months; monthsCounter = monthsCounter + 1)
{
// Add to total variables
totalInterest += interest;
totalPrincipal += principalPayment;
totalPayment += pmt;
// Calculate the principal payment
interest = loan * rate;
principalPayment = (loan * rate * Math.Pow(1 + rate, months)) / (Math.Pow(1 + rate, months) - 1);
pmt = principalPayment + interest;
loan = loan - principalPayment;
// Output data to listbox
loanListBox.Items.Add(String.Format("{0,5}{1,12}{2,12}{3,12}{4,12}", monthsCounter, interest.ToString("N2"), principalPayment.ToString("N2"), pmt.ToString("N2"), loan.ToString("N2")));
}
loanListBox.Items.Add("");
loanListBox.Items.Add(String.Format("{0,5}{1,12}{2,12}{3,12}", "Total", totalInterest.ToString("N2"), totalPrincipal.ToString("N2"), totalPayment.ToString("N2")));
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
This is what my output looks like when running the program:
However, the output is supposed to be this:
The formula you're using for amortization is correct, it's what you do after this that is giving you the wrong result. principalPayment is the total payment which includes interest. You should probably rename this to totalPayment because the name is misleading. If you know the total payment amount, and you know the interest. How are you going to get the principal amount?
Interest + Principal = Total Payment
Update:
Keep in mind that the loan value used in the amortization formula is not changed--the original loan amount is used for all calculations.
Any time you see "???", it means that you need to fill in the code.
You may consider adding a variable:
double originalLoanAmount = 0;
Then put the loan amount into originalLoanAmount.
double.TryParse(loanAmountBox.Text, out originalLoanAmount);
Set initial values before the "for" loop:
originalLoanAmount = ???
balance = ???
How do you calculate the interest?
interest = ???
Calculate total payment: (original loan amount doesn't change)
pmt = (originalLoanAmount * rate * Math.Pow(1 + rate, months)) / (Math.Pow(1 + rate, months) - 1);
What's the principalPayment?
principalPayment = ???
What's the new balance?
balance = ???
So I have 2 list boxes within my form. Listbox1 contains different types of items that have a price and Listbox2 contains how much of that item you want to purchase. How do I update my price label so when I select both options from each list box it updates the label and gives me a price. Here's an example to help you better understand.
I select the $1.50 Chocolate Chip Cookie item in my ListBox1 and in ListBox2 I select the 1 Dozen Cookie item. So I would want my priceLabel to update to $18.00. How would I do this?
As of now I have tried creating some code in the listBox1_SelectedIndexChanged method but I am returned these 3 following values... $0.00...$2.00...$4.00
Here's my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
double index = listBox1.SelectedIndex;
double index2 = listBox2.SelectedIndex;
double total = index * index2;
label9.Text = total.ToString("C");
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label9_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
const int ESTIMATED_ARRIVAL = 3;
label10.Text = monthCalendar1.SelectionStart.AddDays(ESTIMATED_ARRIVAL).ToShortDateString();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
In listBox1_SelectedIndexChanged(object sender, EventArgs e) you use listBox1.SelectedIndex; and listBox2.SelectedIndex;, if you refer to ListBox.SelectedIndex Property
ListBox.SelectedIndex Property
Gets or sets the zero-based index of the currently selected item in a
ListBox.
Property Value
Int32
A zero-based index of the currently selected item. A value of negative one (-1) is returned if no item is selected.
it just return index of selected item, so for your purpose you must get value of selected item.
I hope this code be a good guide for you:
Add handler of SelectedIndexChanged event of both list boxes to this method:
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.listBox1.SelectedIndex > -1 && this.listBox2.SelectedIndex > -1)//You can set default SelectedIndex for list boxes and remove this
{
string s1 = this.listBox1.Items[this.listBox1.SelectedIndex].ToString();
string s2 = this.listBox2.Items[this.listBox2.SelectedIndex].ToString();
//Now we extracting the number from string
//NOTE this is a simple implementation. You must change it as your needs.
//for example
//s1 = $1.50 Chocolate Chip Cookie
//s2 = 1 Dozen Cookie
int index = s1.IndexOf(' ');//get the index of first space after 1.50 (Number) in s1
s1 = s1.Substring(1, index);
index = s2.IndexOf(' ');//get the index of first space after 1 (Number) in s2
s2 = s2.Substring(0, index);
if (double.TryParse(s1, out double p1) && double.TryParse(s2, out double p2))
{
const int DOZEN = 12;
double result = p1 * (p2 * DOZEN);
//or
//remove const int DOZEN = 12; and simply
//double result = p1 * (p2 * 12);
this.label9.Text = result.ToString("C");
}
else
{
MessageBox.Show("Can not parse double values.");
}
}
}
I am very new in C#. I have written a code to get two numbers in two text boxes and basically show their multiplication in a third text box.
The code is like:
private void button1_Click(object sender, EventArgs e)
{
double A = double.Parse(textBox2.Text);
double B = double.Parse(textBox3.Text); //gets the hourly wage
double C = A * B;
}
I have written them all in an executing button class. How can I get "A" and "B" in their own private texbox classes and relate them in "C" text box class?
I need to do it in order to validate the textboxes to give the user an error if he leaves any textboxes empty.
You may restrict user to fill in the text boxes before executing the button logic in this way:
private void button1_Click(object sender, EventArgs e)
{
if(textBox2.Text == string.Empty || textBox3.Text == string.Empty)
{
MessageBox.Show("Invalid input");
return;
}
double A = double.Parse(textBox2.Text);
double B = double.Parse(textBox3.Text); //gets the hourly wage
double C = A * B;
}
This is what u do to display your answer in the third textbox
private void button1_Click(object sender, EventArgs e)
{
if(textBox2.Text == string.Empty || textBox3.Text == string.Empty)
{
MessageBox.Show("Please Fill Both Text Box");
return;
}
double A = double.Parse(textBox2.Text);
double B = double.Parse(textBox3.Text);
textbox4.Text = (A * B).ToString();
}
What I need to do is calculated the value of one field in the grid, based on the values of other fields in the grid. I need to run this calculation After the value in one of the dependent cells is changed, but only if the value was a Valid entry. The EditValueChanged, Validating, and Validated events of the editor/repository all occur before the data is posted back into the datasource. I am wondering if there is any event I can hook into that will allow me to fire this calculation after the data has been post back into the datasource, but before control is returned to the user.
Sample Code
//calculation functions
private void SetCalcROP(MyObjectt Row)
{
//rop = m/hr
TimeSpan ts = Row.ToTime - Row.FromTime;
double diffDepth = Row.EndDepth - Row.StartDepth;
if (ts.TotalHours > 0)//donot divide by 0
Row.ROP = diffDepth / ts.TotalHours;
else
Row.ROP = 0;
}
private void SetCalcDeltaP(MyObject Row)
{
Row.DeltaPress = Row.SPPOnBtm - Row.SPPOffBtm;
}
//events
private void repNumberInput_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
if (vwDDJournal.FocusedColumn.Equals(colSPPOff) || vwDDJournal.FocusedColumn.Equals(colSPPOn))
SetCalcDeltaP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repNumberInput_NoNulls_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
if (vwDDJournal.FocusedColumn.Equals(colStartDepth) || vwDDJournal.FocusedColumn.Equals(colEndDepth))
SetCalcROP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repTimeEdit_Validated(object sender, EventArgs e) //is actaully ActiveEditor_Validated
{
SetCalcROP(vwDDJournal.GetFocusedRow() as MyObject);
}
private void repNumberInput_NoNulls_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextEdit TE = sender as TextEdit;
//null is not valid for this entry;
if (string.IsNullOrEmpty(TE.Text))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column may not be blank");
return;
}
else
{
double tmp;
if (!Double.TryParse(TE.Text, out tmp))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column must contain a number");
return;
}
}
}
private void repNumberInput_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
TextEdit TE = sender as TextEdit;
//null is not valid for this entry;
if (!string.IsNullOrEmpty(TE.Text))
{
double tmp;
if (!Double.TryParse(TE.Text, out tmp))
{
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "This Column must contain a number");
return;
}
}
}
private void repTimeEdit_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
if (vwDDJournal.FocusedColumn.Equals(colToTime))
{//dont bother to check from time
//TIME TRAVEL CHECK!!!!
DateTime FromTime = Convert.ToDateTime(vwDDJournal.GetRowCellValue(vwDDJournal.FocusedRowHandle, colFromTime));
TimeEdit te = sender as TimeEdit;
DateTime ToTime = Convert.ToDateTime(te.EditValue);
if (ToTime < FromTime)
{//TIME TRAVEL
e.Cancel = true;
vwDDJournal.SetColumnError(vwDDJournal.FocusedColumn, "To Time must be greater than From Time");
return;
}
}
}
the problem is that everywhere I call this from, and whether I use vwDDJournal.GetRowCellValue(...) or vwDDJournal.GetFocusedRow() as MyObject, I still get the old edit value.
Requirements
I have to have the input validated before running the calculation.
I have to run the calculation immediately after making the change.
... What I need to do is calculated the value of one field in the grid, based on the values of other fields in the grid.
The best way to accomplish this task is using Unbound Columns feature.
The following example demonstrates how to implement this feature by handling the ColumnView.CustomUnboundColumnData event:
// Provides data for the Total column.
void gridView1_CustomUnboundColumnData(object sender, CustomColumnDataEventArgs e) {
if (e.Column.FieldName == "Total" && e.IsGetData) e.Value =
getTotalValue(e.ListSourceRowIndex);
}
// Returns the total amount for a specific row.
decimal getTotalValue(int listSourceRowIndex) {
DataRow row = nwindDataSet.Tables["Order Details"].Rows[listSourceRowIndex];
decimal unitPrice = Convert.ToDecimal(row["UnitPrice"]);
decimal quantity = Convert.ToDecimal(row["Quantity"]);
decimal discount = Convert.ToDecimal(row["Discount"]);
return unitPrice * quantity * (1 - discount);
}
Original example: How to: Add an Unbound Column Storing Arbitrary Data
You can also implement calculated value for unbound column using expressions:
GridColumn columnTotal = new GridColumn();
columnTotal.FieldName = "Total";
columnTotal.Caption = "Total";
columnTotal.UnboundType = DevExpress.Data.UnboundColumnType.Decimal;
columnTotal.UnboundExpression = "[Quantity] * [UnitPrice] * (1 - [Discount])";
gridView1.Columns.Add(columnTotal);
How about CustomCellValue?
After posting back to the data source refresh the data.
It's called whenever data is updated or view is changed.