I am new to C#. I need the text of lblBalance to remain as it is when the btnNew is clicked, while it changes according to some calculatios when btnCalc is clicked. Here is my attempt so far.
FIGURED IT OUT, Thanks!
private void btnReset_Click(object sender, EventArgs e)
{
//Reset balance to 0.
balance = 0m;
lblBalance.Text = "";
tbDate.Text = "";
//Call the setupForm procedure.
setupForm();
}
private void setupForm()
{
//Setupform done once to reduce amount of times code must be entered.
//Code to clear these entries and set radio and checkboxes to false.
tbDate.Text = "";
tbAmount.Text = "";
rDeposit.Checked = false;
rWithdrawal.Checked = false;
rFee.Checked = false;
chkBank.Checked = false;
//Return focus to the date textbox
tbDate.Focus();
}
private void btnNew_Click(object sender, EventArgs e)
{
//Clear form, but retain balance when clicked.
setupForm();
}
private void tbDate_TextChanged(object sender, EventArgs e)
{
}
private void lblBalance_Click(object sender, EventArgs e)
{
}
private void btnCalc_Click(object sender, EventArgs e)
{
decimal Amount;
Amount = decimal.Parse(tbAmount.Text);
if ((rDeposit.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance + Amount);
}
else if ((rWithdrawal.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance - Amount);
}
else if ((rFee.Checked == true) && (chkBank.Checked == true))
{
Decimal.TryParse(lblBalance.Text, out balance);
lblBalance.Text = Convert.ToString(balance - Amount);
}
if ((rDeposit.Checked == false) && (rWithdrawal.Checked == false) && (rFee.Checked == false))
{
MessageBox.Show("ERROR: You must select Deposit, Withdrawal, or Service Fee.");
}
}
private void rDeposit_CheckedChanged(object sender, EventArgs e)
{
}
}
}
change:
lblBalance.Text += balance.ToString();
to
lblBalance.Text = balance.ToString();
Inside your btnNew_Click event
Related
after clicking my value and pressing my OK_button I cant get the Value out of the listView to save it somewhere else. I cant use listView1.FindItemWithText because I don't have a text to search for.. Idk how to look for the clicked value after I pressed the OK_button
//Create dummy data to display
myData = new string[dataListSize];
for (int i = 0; i < dataListSize; i++)
{
myData[i] = String.Format("{0}", i);
}
}
private void listView1_SearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e)
{
e.Index = Array.FindIndex(myData, s => s == textBox1.Text.ToString());
}
private void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
e.Item = new ListViewItem(myData[e.ItemIndex]);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
String MyString = textBox1.Text.ToString();
ListViewItem lvi = listView1.FindItemWithText(MyString.TrimEnd());
//Select the item found and scroll it into view.
if (lvi != null)
{
listView1.SelectedIndices.Clear();
listView1.SelectedIndices.Add(lvi.Index);
listView1.EnsureVisible(lvi.Index);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e){ }
private void OK_button_Click(object sender, EventArgs e)
{
try
{
// OK -> Daten übernehmen
int iCount = this.listView1.SelectedIndices.Count;
if (iCount != 1)
{
MessageBox.Show("Value is empty");
return;
}
DialogResult = DialogResult.OK;
Close();
}
catch (Exception)
{
//WriteProtokoll(ex.ToString(), 0);
Close();
}
}
I found out that I can get my value with:
string txt = listView1.FocusedItem.Text;
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 = ???
I need the buttons BtnCalculate and BtnMessageBox to be disabled when there is nothing in the TxtQuantity and TxtPrice Text boxes including when the program starts. Does anyone know how to do this? Obviously the "Quantity and price must not be empty" message will not be needed in the code anymore after changes are made. Thank you very much in advance! May be simple but IDK what I am doing.
Here is the CODE:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BtnCalculate_Click(object sender, EventArgs e)
{
//declare Variables
int intQuantity;
Decimal decPrice;
Decimal decTotal;
//make sure quantity and price are the same
// if string is null or empty retuern textbox
Decimal TAX_RATE = 0.06m;
if (OosTax.Checked == true)
{ TAX_RATE = 0.09m; }
if ((TxtQuantity.Text.Trim().Length == 0 || (TxtPrice.Text == "")))
{ MessageBox.Show("Quantity and price must not be empty", "Calculator", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2); }
else
{
try
{
intQuantity = Int32.Parse(TxtQuantity.Text);
decPrice = Decimal.Parse(TxtPrice.Text);
decTotal = (intQuantity * decPrice) * (1 + TAX_RATE);
LblMessage.Text = decTotal.ToString("C");
}
catch (Exception ex)
{ // Send Focus to Quantity
TxtQuantity.Focus();
TxtQuantity.SelectAll();
}
}
}
private void BtnMessageBox_Click(object sender, EventArgs e)
{
//declare Variables
int intQuantity;
Decimal decPrice;
Decimal decTotal;
string message = "Your Total Is: ";
Decimal TAX_RATE = 0.06m;
if (OosTax.Checked == true)
{ TAX_RATE = 0.09m; }
//make sure quantity and price are the same
// if string is null or empty retuern textbox
if ((TxtQuantity.Text.Trim().Length == 0 || (TxtPrice.Text == "")))
{ MessageBox.Show("Quantity and price must not be empty", "Calculator", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2); }
else
{
try
{
intQuantity = Int32.Parse(TxtQuantity.Text);
decPrice = Decimal.Parse(TxtPrice.Text);
decTotal = (intQuantity * decPrice) * (1 + TAX_RATE);
// Display Total Currency as
MessageBox.Show(message + System.Environment.NewLine + decTotal.ToString("C"), "Chapter Two",
MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
catch (Exception ex)
{ // Send Focus to Quantity
TxtQuantity.Focus();
TxtQuantity.SelectAll();
}
}
}
private void BtnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void BtnClear_Click(object sender, EventArgs e)
{
LblMessage.Text = String.Empty;
}
}
use TextChanged event on textbox
like this
private void textBox1_TextChanged(object sender, EventArgs e)
{
button1.Enabled = (textBox1.Text.Length > 0);
}
if you wish to do this on window loaded,
use
textBox1_TextChanged(null,null);
on loaded event
I would just write a method that sets the button enabled property based on the textbox text length of the two textbox controls, and then call it from the form Load event and the TextChanged event of the textboxes:
private void Form1_Load(object sender, EventArgs e)
{
ButtonEnabler();
}
private void txtPrice_TextChanged(object sender, EventArgs e)
{
ButtonEnabler();
}
private void txtQuantity_TextChanged(object sender, EventArgs e)
{
ButtonEnabler();
}
private void ButtonEnabler()
{
bool enabled = txtPrice.TextLength > 0 && txtQuantity.TextLength > 0;
btnCalculate.Enabled = enabled;
btnMessageBox.Enabled = enabled;
}
I made this calculator in C# and I have one problem: When I press keyboard something like 1 it gives me incorrect result double number. I don't get the correct result.
Do you know what I am doing wrong,
Thank you very much!
namespace Calculator
{
public partial class Calculator : Form
{
Double value = 0;
String operation = "";
int i = 0;
bool operation_pressed = false;
bool button_dot = false;
OperationClass class1 = new OperationClass();
public Calculator()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Calculator_KeyPress);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Calculator_Load(object sender, EventArgs e)
{
}
private void Calculator_KeyPress(object sender, KeyPressEventArgs e)
{
if ((result.Text == "0") || (operation_pressed))
result.Clear();
switch (e.KeyChar)
{
// key press from 0-9
case (char)48:
case (char)49:
case (char)50:
case (char)51:
case (char)52:
case (char)53:
case (char)54:
case (char)55:
case (char)56:
case (char)57:
e.Handled = true;
result.Text += e.KeyChar.ToString();
break;
}
}
private void button_Click(object sender, EventArgs e)
{
if ((result.Text == "0") || (operation_pressed))
result.Clear();
operation_pressed = false;
Button b = (Button)sender;
result.Text = result.Text + b.Text;
}
private void operator_click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text;
value = Double.Parse(result.Text);
operation_pressed = true;
equation.Text = value + " " + operation;
}
private void buttonCE_Click(object sender, EventArgs e)
{
result.Text = "0";
equation.Text = "";
button_dot = false;
}
private void buttonC_Click(object sender, EventArgs e)
{
result.Clear();
value = 0;
}
private void buttonEqual_Click(object sender, EventArgs e)
{
equation.Text = "";
button_dot = false;
operation_pressed = true;
if (operation != "")
result.Text = class1.GetResult(operation, value, result.Text);
else
result.Text = result.Text + "";
}
private void buttonDot_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if ((!button_dot && !operation_pressed) || result.Text == "0")
result.Text = result.Text + b.Text;
button_dot = true;
}
}
}
You don't need to append keychar in your result.Text (Assuming result is your TextBox item) as you have written in line result.Text += e.KeyChar.ToString();. That's the line which is doubling your input.
Remove it and it'll work as expected.
I'd change it from keypress to KeyUp instead. That way it only fires as soon as the key is released.
Edit: Check out this info: Difference between the KeyDown Event, KeyPress Event and KeyUp Event in Visual Studio
I am in in study phase of asp.net so decided to do an online calculator. The issue is when i do a calculation 1 + 5 = it does not give any output at all. I tried a debugging.
Click button 1 :
first value = 1;
click button + :
first value = null;
click button 5 :
first value = 5
click button =
NOTHING :)
Here is my c# code :
public partial class _Default : System.Web.UI.Page
{
string firstOperand;
string secondOperand;
string Operator;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnOff_Click(object sender, EventArgs e)
{
txtScreen.Enabled = false;
ClearVariables();
}
protected void btnOn_Click(object sender, EventArgs e)
{
txtScreen.Enabled = true;
ClearVariables();
}
private void ClearVariables()
{
firstOperand = "";
secondOperand = "";
Operator = "";
}
protected void Operand(string value)
{
if (value == null) return;
try
{
txtScreen.Text = value;
if (firstOperand == null)
{
firstOperand = value;
}
else
{
if (Operator == null)
{
firstOperand.Insert(firstOperand.Length, value);
}
else
{
secondOperand.Insert(secondOperand.Length, value);
}
}
}
catch (Exception ex)
{
}
}
protected void Num1_Click(object sender, EventArgs e)
{
txtScreen.Text = Num1.Text;
Operand(Num1.Text);
}
protected void Num2_Click(object sender, EventArgs e)
{
txtScreen.Text = Num2.Text;
Operand(Num2.Text);
}
protected void Num3_Click(object sender, EventArgs e)
{
txtScreen.Text = Num3.Text;
Operand(Num3.Text);
}
protected void Num4_Click(object sender, EventArgs e)
{
txtScreen.Text = Num4.Text;
Operand(Num4.Text);
}
protected void Num5_Click(object sender, EventArgs e)
{
txtScreen.Text = Num5.Text;
Operand(Num5.Text);
}
protected void Num6_Click(object sender, EventArgs e)
{
txtScreen.Text = Num6.Text;
Operand(Num6.Text);
}
protected void Num7_Click(object sender, EventArgs e)
{
txtScreen.Text = Num7.Text;
Operand(Num7.Text);
}
protected void Num8_Click(object sender, EventArgs e)
{
txtScreen.Text = Num8.Text;
Operand(Num8.Text);
}
protected void Num9_Click(object sender, EventArgs e)
{
txtScreen.Text = Num9.Text;
Operand(Num9.Text);
}
protected void Num0_Click(object sender, EventArgs e)
{
txtScreen.Text = Num0.Text;
Operand(Num0.Text);
}
protected void btnClr_Click(object sender, EventArgs e)
{
txtScreen.Text = "";
ClearVariables();
}
protected void OpDiv_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpDiv.Text;
}
}
protected void OpMul_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpMul.Text;
}
}
protected void OpSub_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpSub.Text;
}
}
protected void OpAdd_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
txtScreen.Text = "";
Operator = OpAdd.Text;
}
}
protected void OpEqual_Click(object sender, EventArgs e)
{
if (firstOperand == null && Operator == null)
{
return;
}
else if (firstOperand != null && Operator != null && secondOperand == null)
{
secondOperand = firstOperand;
}
else
{
double num1;
double num2;
try
{
num1 = Double.Parse(firstOperand);
num2 =Double.Parse(secondOperand);
{
switch (Operator)
{
case "+":
num1 += num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
case "-":
num1 -= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
case "/":
if (num2 == 0)
{
txtScreen.Text = "Divison by zero";
}
else
{
num1 /= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
}
break;
case "*":
num1 *= num2;
firstOperand = num1.ToString();
txtScreen.Text = firstOperand;
break;
default: txtScreen.Text = "Invalid Operation";
break;
}
}
}
catch (Exception ex)
{
txtScreen.Text = "Not a valid Number";
ClearVariables();
}
}
ClearVariables();
}
protected void OpDot_Click(object sender, EventArgs e)
{
if (firstOperand != null)
{
if (Operator == null)
{
firstOperand.Insert(firstOperand.Length, ".");
}
else
{
secondOperand.Insert(secondOperand.Length, ".");
}
}
}
}
Could someone explain what is happening? And how to resolve the same.
Thanks
OK. Its simple here, your values are refreshing on postback. so simply hold the values in viewstate.
And before that do reduce your code lines.
you have
protected void Num5_Click(object sender, EventArgs e)
{
txtScreen.Text = Num5.Text;
Operand(Num5.Text);
}
arround 10 events like this. so do first make it a single event like
protected void Num_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
txtScreen.Text = btn.Text;
Operand(btn.Text);
}
and assign this event as Click event for every numeric button
Now in Operand Method make something like
private void Operand(string value)
{
if(ViewState["FirstOperand"] == null)
ViewState["FirstOperand"] = value;
else if(ViewState["SecondOperand"] == null)
ViewState["SecondOperand"] = value;
}
similarly reduce you code for add, sub, mul, divide operator click events as i just showed above for numeric button click events.
and also set the operator value in ViewState["Operator"].
and finally in your OpEqual_Click event. initally set first and second operand like
if(ViewState["FirstOperand"] != null)
firstOperand = ViewState["FirstOperand"].ToString();
if(ViewState["SecondOperand"] != null)
secondOperand = ViewState["SecondOperand"].ToString();
if(ViewState["Operator"] != null)
Operator = ViewState["Operator"].ToString();
Hope this helps
It appears to me that your problem is in your ASP.Net environment and/or your IDE, rather than in your code. I do not know ASP.Net well, but it I do know C# and I notice these two odd facts:
Your debugging shows firstOperand being reset to null or the current operand after every event.
But, you code never sets firstOperand to null. It does set it to the empty string("") in clearVariables, but that is not the same as null ("" != null).
Therefore, I must conclude that something other than your code is setting firstOperand to null. The most logical source of that would be your execution/debugging environment which does reset all object and string variables to null when it initializes for execution, or when it invokes a new Page, Class, Method, etc. (for any variable scoped to those).
Of course you don't want it to do that for every button click, so I have to assume that there is something set wrong in your environment/setup that is causing this.
Hopefully, someone who knows ASP.Net better then I do can explain the rest ...
Yes At last I found it.
It is the problem with sessions. Every time I click button, a new session invokes and all the value resets. So We need to add values in session and recover it.
Like :
Session["Calc"] = firstOperand + ",";
Session["Calc"] += secondOperand + ",";
Session["Calc"] += Operator + ",";
and at page load:
try
{
var Data = Session["Calc"].ToString().Split(',');
if(Data[0] != "")
firstOperand = Data[0];
if (Data[1] != "")
Operator = Data[1];
if (Data[2] != "")
secondOperand = Data[2];
}
catch(Exception ex)
{
}
It is not a good solution I think(still studying asp :) ). And I can use if condition since number of item is fixed to 3.