I've created a Mortgage Calculator via WPF on visual studio 2012. The design looks like this:

Enter Loan amount: TextBox here

Enter Loan Duration:

15 years(Radio Button)

30 years(Radio Button)

Other(Radio Button) with TextBox

Select Interest Rate: ComboBox here

Button here to calculate

The issue i'm having trouble with coding the math formula properly with the textbox, radio buttons, and combobox all in the formula. I'm having problems getting the selected item in the combobox in the equation correctly and the radio buttons as well. As of now when I run the program and caluculate it It says "The Amount of the monthly payment is: NaN"

Here is my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplicationCALC
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void ButtonCal_Click(object sender, RoutedEventArgs e)
    {
        double p;
        float r;
        double n;


        if (!double.TryParse(Textboxloan.Text, out p))
            MessageBox.Show("Please Enter a Valid Amount", "Incorrect Data");
        if (double.TryParse(Textboxother.Text, out n))
         MessageBox.Show("Please Enter a Valid Length. \n Amount given is: " + Textboxother.Text);
        if (Radio15.IsChecked== true)
        {
            n = 15;
        }
        if (Radio30.IsChecked == true)
        {
            n = 30;
        }
        if (float.TryParse(InterestRateCB.SelectedItem.ToString(), out r))
            MessageBox.Show("Enter a Valid Interest Rate");



        double top = p * r / 1200.00;
        double bottom = 1 - Math.Pow(1.0 + r / 1200.0, -12.0 * n);
        double monthly = top / bottom;
        string MonthPay = string.Format("The amount of the monthly payment is: {0:c}", monthly);
        MessageBox.Show(MonthPay);
    }


    private void Radio_Checked(object sender, RoutedEventArgs e)
    {
        if (RadioOther.IsChecked == true)
        {
            Textboxother.IsEnabled = true;
        }
        else
        {
            Textboxother.IsEnabled = false;
        }
    }

    private void InterestRateCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem cpi = InterestRateCB.SelectedItem as ComboBoxItem;
        string str = (string)cpi.Content;
    }


    } 
  }

Recommended Answers

All 9 Replies

Hi Ahmed_51 and welcome to DaniWeb

So, p is principle, r is rate (in percentage) and n is number of years of the loan. I'm not sure I follow your calculation, but I would think it would be something like (principle x rate x number of years) / (number of months), so your variable named top becomes p * ((100 + r) / 100) * n (don't forget the brackets - precedence matters!) and your variable named bottom is 12 * n.

Consider example of $100,000 loan at 10% interest over 15 years. Total payment is $100,000 x ((100+10)/100) x 15 = $165,000 and number of months in 15 years is 15 x 12 = 180, so monthly repayment is $165,000 / 180 = $916.67 (rounded).

Unless you are attempting some type of compound interest formula?

Thank you, yes you're correct
p = principal (dollars), n = number of years, r = interest rate (percent), m = monthly payment (dollars).

This is the formula I was given to use in the program using
the .Net function call Math.pow(x, y) to compute xy (x raised to the y power).

M =

           p r / 1200.0
 ________________________________________
     1 - (1.0 + r / 1200.0) -12.0 n

So I just rewrote the top part is the top = p * r /1200.00
and the bottom as bottom = 1 - Math.pow(1.0 + r / 1200.0, -12.0 * n)
Then just did top / bottom.

I think the mistakes are here specifically in the code, just don't know what i've done wrong:

 if (!double.TryParse(Textboxloan.Text, out p))
     MessageBox.Show("Please Enter a Valid Amount", "IncorrectData");
    if (double.TryParse(Textboxother.Text, out n))
         MessageBox.Show("Please Enter a Valid Length. \n Amount given is: " + Textboxother.Text);
    if (Radio15.IsChecked== true)
    {
        n = 15;
    }
    if (Radio30.IsChecked == true)
    {
        n = 30;
    }
    if (float.TryParse(InterestRateCB.SelectedItem.ToString(), out r))
        MessageBox.Show("Enter a Valid Interest Rate");

Just a quick perusal shows 2 things:

if (double.TryParse(Textboxother.Text, out n))
    MessageBox.Show("Please Enter a Valid Length. \n Amount given is: " + Textboxother.Text);

if (float.TryParse(InterestRateCB.SelectedItem.ToString(), out r))
 MessageBox.Show("Enter a Valid Interest Rate");

Both of these should be using the '!' operator.

Interesting when I made those changes adding the "!" on, when running the program now and entering values after calculating it returns the Messagebox.Show errors i've setup "Please enter a Valid Length" and "Enter a Valid Interest Rate"

I would suggest that the text values aren't being parsed to numbers. Thus the messageboxes.

One possible explanation is you're entering the numbers based on a different culture than what your code is expecting. For instance some cultures use , for decimal and parsing it will succeed. Others use the , for 1000's separation and parsing it will fail.

Another explanation is your logic needs to be refined. I would suggest trying to parse Textboxother.Text only if both radiobuttons IsChecked is false. Something like this might work:

if (Radio15.IsChecked== true)
{
    n = 15;
}
else
    if (Radio30.IsChecked == true)
    {
        n = 30;
    }
else
    if (!double.TryParse(Textboxother.Text, out n))
    {
        MessageBox.Show("Please Enter a Valid Length. \n Amount given is: " + Textboxother.Text);
        //If you get an invalid input stop the calculation.
        return;
    }

ok, I refined the logic as you said for all the radio buttons and other textbox. Now when running the code It returns the the MessageBox.Show error for the interest rate only, "Please enter a valid interest rate" I wonder if it could be my values for the interest rate combobox:

if (!float.TryParse(InterestRateCB.SelectedItem.ToString(), out r))
            MessageBox.Show("Enter a Valid Interest Rate");

My values for the combobox are 1.0 - 5.0 going up .5 each time.

It might have something to do with how you're filling the combobox. Here's one way that will make sure that all the values will parse to numbers:

cb1.ItemsSource = (from i in Enumerable.Range(10, 45)
                   where i % 5 == 0
                   select ((double)i / 10.0));

Since each item is in fact a double, you can use a direct cast:

r = (double)InterestRateCB.SelectedItem;

Another option is to use a NumericUpDown control instead.

Thanks for the help,

after adding I got an error at this point in the code:

InterestRateCB.ItemsSource = (from i in Enumerable.Range(10, 45)
                           where i % 5 == 0
                           select ((double)i / 10.0));

I get this InvalidOperationException error when trying calculation:

Items collection must be empty before using ItemsSource.

Clear all items from the combobox in the designer, or run the Clear() method of the Items collection before you set the ItemsSource property.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.