Getting dynamic data from calculation  to display in data grid  (no database)

Posted on 2006-06-03
Last Modified: 2006-11-18
Hello everyone,

I'm in my last week of class. I have made quite a bit of progress getting my mortgage calculator from a stand alone to a web application using codebehind. But I'm having trouble getting my amortization table data into a data grid. Here is what I have so far. When I run it I get an error message saying that  Object reference not set to an instance of an object. and an error on Line 40:         DisplayAmortTable.DataSource = AmortTable()

The files can be downloaded at the following url


------ mortgagecodefile.vb ------------------------------------------

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Data

Public Class myCodeBehind
    Inherits Page
    'list all form elements that are used in the programming

    Protected WithEvents myLabel As Label
    Protected WithEvents MyGrid As DataGrid
    Protected WithEvents DisplayAmortTable As DataGrid
    Protected WithEvents uiMortgageAmountTextBox As TextBox
    Protected WithEvents uiDisplayPaymentLabel As TextBox
    Protected WithEvents uiMortgageTermTextBox As TextBox
    Protected WithEvents uiInterestRateTextBox As TextBox
    Protected WithEvents uiAmortTableRichTextBox As TextBox
    Protected WithEvents uiLoanTypeListBox As ListBox
    Protected WithEvents uiCalculateButton As Button

    'Global declaration of variables

    Dim MortgageTerm As Double
    Dim MortgageAmount As Double
    Dim Payment As Double
    Dim InterestRate As Double
    Sub ResetForm(ByVal sender As Object, ByVal e As System.EventArgs)
        'reset form function
        uiMortgageAmountTextBox.Text = ""
        uiMortgageTermTextBox.Text = ""
        uiDisplayPaymentLabel.Text = ""
        uiInterestRateTextBox.Text = ""
    End Sub
    'Call calculate functions based on whether there are values in the text boxes
    Sub ASPCalcuate(ByVal s As Object, ByVal e As EventArgs)

        Payment = CalculatePayment()
        uiDisplayPaymentLabel.Text = Payment.ToString("c2")
        DisplayAmortTable.DataSource = AmortTable()

    End Sub

    Function CalculatePayment()
        'calculates the payment if there are values entered in the text boxes
        MortgageAmount = uiMortgageAmountTextBox.Text
        MortgageTerm = uiMortgageTermTextBox.Text ' * 12 'calcualtes the mortgage term based on the value entered in the Mortgage Term Field
        InterestRate = uiInterestRateTextBox.Text ' / 100) / 12

        Return (MortgageAmount * (InterestRate / 100) / 12) / (1 - Math.Pow(1 + (InterestRate / 100) / 12, -(MortgageTerm * 12)))

    End Function
    Function AmortTable()
        'sets all the values and calculates number of payments, balance, monthly interst paid, and monthly principal balance
        MortgageAmount = uiMortgageAmountTextBox.Text
        MortgageTerm = uiMortgageTermTextBox.Text ' * 12 'calcualtes the mortgage term based on the value entered in the Mortgage Term Field
        InterestRate = uiInterestRateTextBox.Text ' / 100) / 12

        'variable declarations for looping function
        Dim Balance, MonthlyInterestPayment, MonthlyPrincipalPaid, PrincipalBalance, Rate, NewBalance As Double 'balance of the mortgage after payment is subtracted...not really a true balance because it includes the interest payment.
        Dim NumberPayments = MortgageTerm * 12

        'variable declarations for the data grid
        Dim dt As DataTable = New DataTable
        Dim dr As DataRow

        NumberPayments = 1
        Balance = MortgageAmount 'original amount
        Rate = (InterestRate / 100) / 12 'annual interest rate
        Payment = (MortgageAmount * (InterestRate / 100) / 12) / (1 - Math.Pow(1 + (InterestRate / 100) / 12, -(MortgageTerm * 12)))

        'declaring the first table row with column heading for amortization table
        dt.Columns.Add(New DataColumn("Number Payments", GetType(Double)))
        dt.Columns.Add(New DataColumn("Interest Payment", GetType(Double)))
        dt.Columns.Add(New DataColumn("Balance", GetType(Double)))

        'start of the do loop
            MonthlyInterestPayment = Balance * Rate 'calculate monthly interest rate
            MonthlyPrincipalPaid = Payment - MonthlyInterestPayment 'calculate the principle paid for that month
            'new balance subtracting the amount of the monthly principal paid from the new balance
            NewBalance = Balance - MonthlyPrincipalPaid 'declares new balance after last payment was subtracted from running balance

            'declaring the first dynamic row of the table
            dr = dt.NewRow()
            dr(0) = NumberPayments
            dr(1) = MonthlyInterestPayment
            dr(2) = NewBalance

            Balance = NewBalance        'new balance
            NumberPayments = NumberPayments + 1

            'declare next row

        Loop Until NumberPayments = MortgageTerm * 12

        'create data view and display table (I hope!)
        Dim dv As New DataView(dt)
        Return dv

    End Function

End Class

-----mortgage.aspx file -------------------------------

<%@ page Language="vb" inherits="myCodeBehind" src="mortgagecodefile.vb" %>
<%@ Import Namespace="System.Data" %>
<head><title>Nancy's Mortgage Calculator</title></head>
<script language='JavaScript'>
function SetFocus()
window.onload = SetFocus;
// -->


<H3>Nancy's Mortgage Calculator</H3>
<form Runat="Server" ID="MortgageCalculatorForm" action="mortgage.aspx">

<table width="550" cellspacing="0">
        <td colspan="3" bgcolor="#FFFFCC">Enter the mortgage amount... </td>
<!--Age textbox and validation attempt which did not work -->
  <asp:TextBox id="minMortgageAmount" text="0" runat="server" visible="False" />
  <asp:TextBox id="maxMortgageAmount" text="10000000" runat="server" visible="False" />

            <td>Mortgage Amount:
            Runat="Server" />
            <!--adding validation to be sure that a number is entered in the Mortgage Amount Field -->
                  <asp:RequiredFieldValidator runat="server"
                        id="reqMortgageAmount" ControlToValidate="uiMortgageAmountTextBox"
                        ErrorMessage = "Please enter a number in this text box."
                        display="Dynamic" />
            <td colspan="2" bgcolor="#FFFFCC">Then enter the Mortgage Term and Rate ... </td>
            <td  bgcolor="#FFFFCC">Or Choose One...
            <td>Mortgage Term:
            Runat="Server" />
            <td rowspan="4">
                  <asp:ListBox ID="uiLoanTypeListBox" RunAt="server">
                  <asp:ListItem Text="7 years @ 5.35%" RunAt="server" />
                  <asp:ListItem Text="15 years @ 5.5%" RunAt="server" />
                  <asp:ListItem Text="30 years @ 5.75%" RunAt="server" />
            <td>Interest Rate:
            Runat="Server" />
        <td colspan="3">&nbsp; </td>
        <td colspan="3" bgcolor="#FFFFCC">Your Monthly Payment Is: </td>
                  Runat="Server" />
                        Runat="Server" ID="CalculateButton"/>
                        Text="Reset Form"
                        Runat="Server" ID="ResetButton"/>
            <td colspan="3">
                  text="Amortization Table"

Question by:nflowers1228
    LVL 6

    Accepted Solution

    DisplayAmortTable is null,
    your datagrid name is either:AmortTable OR MyGrid
    see your source file, no datagrid with the ID = "DisplayAmortTable"..
    in your code, instead of this:
            DisplayAmortTable.DataSource = AmortTable()
    Do this:
            MyGrid.DataSource = AmortTable()


    Author Comment

    yes that was it. Thank you very much. I was making myself crazy over something so simple! Thanks again!

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    I have developed many web applications with asp & and to add and use a dropdownlist was always a very simple task, but with the new, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
    Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
    Internet Business Fax to Email Made Easy - With eFax Corporate (, you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    794 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now