Click here to Skip to main content
15,886,137 members

dynamic gridview rebinding problem

ChandanBadgujar asked:

Open original thread
Hi,
I am doing the loan calculator and in that I am facing some gridview related problems. so please help me out!!!!!!!!!!
I have taken the template field in grid view like........
XML
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" EnableViewState="true">
                <Columns>
                    <asp:BoundField HeaderText="No." DataField="No" />
                    <asp:BoundField HeaderText="Payment Date" DataField="PaymentDate" />
                    <asp:BoundField HeaderText="Beginning Balance" DataField="BeginningBalance" />
                    <asp:BoundField HeaderText="Scheduled Payment" DataField="ScheduledPayment" />
                    <%-- <asp:BoundField HeaderText="Extra Payment" DataField="ExtraPayment" /> --%>
                    <asp:TemplateField HeaderText="Extra Payment">
                        <ItemTemplate>
                            <asp:TextBox ID="txtExtraPayment" Text="0" EnableViewState="true" AutoPostBack="true"
                                runat="server" OnTextChanged="txtExtraPayment_TextChanged" DataField="ExtraPayment"
                                Width="75"></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField HeaderText="Total Payment" DataField="TotalPayment" />
                    <asp:BoundField HeaderText="Principal" DataField="principal" />
                    <asp:BoundField HeaderText="Interest" DataField="interest" />
                    <asp:BoundField HeaderText="Ending Balance" DataField="EndingBalance" />
                </Columns>
            </asp:GridView>


now i have created one create grid function in which i have creted first row dynamically and then another loop for second to further rows based on the calculation of the first row. so i have to do the dynamic gridview is must.
i have not used any database for this puppose.
the code is as ................
C#
protected void createGrid()
    {
        loanYears = Convert.ToDecimal(txtLoanYears_BoundControl.Text.Trim());
        scheduledNumberOfPayment = loanYears * 12;
        txtScheduledNumberOfPayments.Text = scheduledNumberOfPayment.ToString();

        // Grid Column Calculations

        // 1) Payment Date


        // 2) Begining Balance
        beginingBal = Convert.ToDecimal(txtLoanAmount.Text.Trim());



        // 3) Scheduled Monthly Payment
        annInterest = Convert.ToDecimal(txtAnnInterest_BoundControl.Text.Trim());

        Double roi = fn_InterestRate(Convert.ToDouble(annInterest));

        Double LY = Convert.ToDouble(loanYears);
        Double BBal = Convert.ToDouble(beginingBal);

        Double emi = fn_ScheduledMonthlyPayment(roi, LY, BBal);

        scheduledMonthlyPayment = Convert.ToDecimal(emi);
        txtScheduledMonthlyPayment.Text = scheduledMonthlyPayment.ToString("C");

        // 4) Optional extra payment
        optionalPayment = Convert.ToDecimal(0.00d);

        // 5) Total Payment
        totalPayment = fn_TotalPayment(scheduledMonthlyPayment, Convert.ToDecimal(txtOptionalPayment.Text.Trim()));

        // 6) Interest
        currentInterest = fn_CurrentInterest(beginingBal, annInterest);

        // 7) Calculating principal amount
        principal = fn_Principal(totalPayment, currentInterest);

        // 8) Ending balance
        endingBal = fn_EndingBalance(beginingBal, principal);

        indexNo = indexNo + 1;
        if (dt.Rows.Count < 1)
        {
            dt.Columns.Add("No", typeof(int));
            dt.Columns.Add("PaymentDate", typeof(string));
            dt.Columns.Add("BeginningBalance", typeof(string));
            dt.Columns.Add("ScheduledPayment", typeof(string));
            dt.Columns.Add("ExtraPayment", typeof(string));
            dt.Columns.Add("TotalPayment", typeof(string));
            dt.Columns.Add("principal", typeof(string));
            dt.Columns.Add("interest", typeof(string));
            dt.Columns.Add("EndingBalance", typeof(string));

            dtRow = dt.NewRow();

            dtRow["No"] = "" + indexNo;
            dtRow["PaymentDate"] = "" + txtStartDateOfLoan.Text;
            dtRow["BeginningBalance"] = beginingBal.ToString("C");
            dtRow["ScheduledPayment"] = "" + scheduledMonthlyPayment.ToString("C");
            dtRow["ExtraPayment"] = "" + optionalPayment.ToString("C");
            dtRow["TotalPayment"] = "" + totalPayment.ToString("C");
            dtRow["principal"] = "" + principal.ToString("C");
            dtRow["interest"] = "" + currentInterest.ToString("C");
            dtRow["EndingBalance"] = "" + endingBal.ToString("C");

            dt.Rows.Add(dtRow);
        }

        if (dt.Rows.Count >= 1)
        {
            for (int i = 1; i < 360; i++)
            {

                // 1) Increment date by a month
                rowCount = dt.Rows.Count - 1;
                o = dt.Rows[rowCount]["PaymentDate"];
                date = Convert.ToDateTime(o).AddMonths(1);
                string n = date.ToShortDateString();

                if (date.Month == 12)
                {
                    // GridView1.Rows[rowCount+1].Cells[4].CssClass = "txtBG";
                }
                //date = DateTime.ParseExact(Convert.ToString(o), "d", "");



                // 2) Begining balance from last ending balance
                beginingBal = Convert.ToDecimal(remoFirstChar(dt.Rows[rowCount]["EndingBalance"].ToString()));


                // 3) Scheduled payment remains constant

                // 4) Extra payment will set to its default value 0

                // 5) Total payment
                schPay = remoFirstChar(dt.Rows[rowCount]["ScheduledPayment"].ToString());
                extPay = remoFirstChar(dt.Rows[rowCount]["ExtraPayment"].ToString());

                totalPayment = fn_TotalPayment(Convert.ToDecimal(schPay), Convert.ToDecimal(extPay));


                // 6) Interest count
                currentInterest = fn_CurrentInterest(beginingBal, annInterest);


                // 7) Principal
                principal = fn_Principal(totalPayment, currentInterest);


                // 8) Ending Balance
                endingBal = fn_EndingBalance(beginingBal, principal);


                indexNo = indexNo + 1;

                dtRow = dt.NewRow();

                dtRow["No"] = "" + indexNo;
                dtRow["PaymentDate"] = "" + n;
                dtRow["BeginningBalance"] = "" + beginingBal.ToString("C");
                dtRow["ScheduledPayment"] = "" + scheduledMonthlyPayment.ToString("C");
                dtRow["ExtraPayment"] = "" + optionalPayment.ToString("C");
                dtRow["TotalPayment"] = "" + totalPayment.ToString("C");
                dtRow["principal"] = "" + principal.ToString("C");
                dtRow["interest"] = "" + currentInterest.ToString("C");
                dtRow["EndingBalance"] = "" + endingBal.ToString("C");

                dt.Rows.Add(dtRow);
            }
        }
        GridView1.DataSource = dt;
        Session["tempDt"] = dt;
        GridView1.DataBind();
    }

Then i am using the gridview texbox's checkedchange event to calculate the further loan amount if extra payment payed. so I create and bind the rows again here....
code..........
C#
protected void txtExtraPayment_TextChanged(object sender, EventArgs e)
    {
        TextBox txtsample = (TextBox)sender;
        GridViewRow gvr = (GridViewRow)txtsample.Parent.Parent;
        int index = gvr.RowIndex;

        dt = (DataTable)Session["tempDt"];

        

        loanYears = Convert.ToDecimal(txtLoanYears_BoundControl.Text.Trim());
        scheduledNumberOfPayment = loanYears * 12;
        txtScheduledNumberOfPayments.Text = scheduledNumberOfPayment.ToString();

        // Grid Column Calculations

        // 1) Payment Date                

        //*******************************************************************
        // 2) Begining Balance
        beginingBal = Convert.ToDecimal(txtLoanAmount.Text.Trim());
        //*******************************************************************


        // 3) Scheduled Monthly Payment
        annInterest = Convert.ToDecimal(txtAnnInterest_BoundControl.Text.Trim());

        Double roi = fn_InterestRate(Convert.ToDouble(annInterest));
        Double LY = Convert.ToDouble(loanYears);
        Double BBal = Convert.ToDouble(beginingBal);
        Double emi = fn_ScheduledMonthlyPayment(roi, LY, BBal);

        scheduledMonthlyPayment = Convert.ToDecimal(emi);
        txtScheduledMonthlyPayment.Text = scheduledMonthlyPayment.ToString("C");

        // 4) Optional extra payment
        optionalPayment = Convert.ToDecimal(txtOptionalPayment.Text.ToString());

        // 5) Total Payment
        totalPayment = fn_TotalPayment(scheduledMonthlyPayment, Convert.ToDecimal(txtOptionalPayment.Text.Trim()));

        // 6) Interest
        currentInterest = fn_CurrentInterest(beginingBal, annInterest);

        // 7) Calculating principal amount
        principal = fn_Principal(totalPayment, currentInterest);

        // 8) Ending balance
        endingBal = fn_EndingBalance(beginingBal, principal);

        indexNo = indexNo + 1;

        if (dt.Rows.Count < 1)
        {
            dt.Columns.Add("No", typeof(int));
            dt.Columns.Add("PaymentDate", typeof(string));
            dt.Columns.Add("BeginningBalance", typeof(string));
            dt.Columns.Add("ScheduledPayment", typeof(string));
            dt.Columns.Add("ExtraPayment", typeof(string));
            dt.Columns.Add("TotalPayment", typeof(string));
            dt.Columns.Add("principal", typeof(string));
            dt.Columns.Add("interest", typeof(string));
            dt.Columns.Add("EndingBalance", typeof(string));

            dtRow = dt.NewRow();

            dtRow["No"] = "" + indexNo;
            dtRow["PaymentDate"] = "" + txtStartDateOfLoan.Text;
            dtRow["BeginningBalance"] = beginingBal.ToString("C");
            dtRow["ScheduledPayment"] = "" + scheduledMonthlyPayment.ToString("C");
            dtRow["ExtraPayment"] = "" + optionalPayment.ToString("C");
            dtRow["TotalPayment"] = "" + totalPayment.ToString("C");
            dtRow["principal"] = "" + principal.ToString("C");
            dtRow["interest"] = "" + currentInterest.ToString("C");
            dtRow["EndingBalance"] = "" + endingBal.ToString("C");

            dt.Rows.Add(dtRow);
        }

        if (dt.Rows.Count >= 1)
        {
            for (int i = 1; i < 360; i++)
            {
                // 1) Increment date by a month 
                rowCount = dt.Rows.Count - 1;
                o = dt.Rows[rowCount]["PaymentDate"];
                date = Convert.ToDateTime(o).AddMonths(1);
                string n = date.ToShortDateString();
                //date = DateTime.ParseExact(Convert.ToString(o), "d", "");                    

                //2) Begining balance from last ending balance 
                beginingBal = Convert.ToDecimal(remoFirstChar(dt.Rows[rowCount]["EndingBalance"].ToString()));


                //3) Scheduled payment remains constant 

                //4) Extra payment will set to its default value 0 


                // 5) Total payment ***
                int ind = dt.Rows.Count;

                schPay = remoFirstChar(dt.Rows[rowCount]["ScheduledPayment"].ToString());
                if (ind == index)
                {
                    extPay = txtsample.Text;
                    extPay = Convert.ToDecimal(extPay);
                }
                else
                {
                    extPay = 0.00;
                    extPay = Convert.ToDecimal(extPay);
                }
                totalPayment = fn_TotalPayment(Convert.ToDecimal(schPay), Convert.ToDecimal(extPay));

                // 6) Interest count 
                //annInterest = Convert.ToDecimal(txtAnnInterest_BoundControl.Text.Trim());
                currentInterest = fn_CurrentInterest(beginingBal, annInterest);

                // 7) Principal                     
                principal = fn_Principal(totalPayment, currentInterest);

                // 8) Ending Balance 
                endingBal = fn_EndingBalance(beginingBal, principal);

                indexNo = indexNo + 1;

                dtRow = dt.NewRow();

                dtRow["No"] = "" + indexNo;
                dtRow["PaymentDate"] = "" + n;
                dtRow["BeginningBalance"] = "" + beginingBal.ToString("C");// dt.Rows[rowCount]["EndingBalance"];
                dtRow["ScheduledPayment"] = "" + scheduledMonthlyPayment.ToString("C");
                
                
                dtRow["ExtraPayment"] = "$" + extPay.ToString();
                dtRow["TotalPayment"] = "" + totalPayment.ToString("C");                
                dtRow["principal"] = "" + principal.ToString("C");
                dtRow["interest"] = "" + currentInterest.ToString("C");
                dtRow["EndingBalance"] = "" + endingBal.ToString("C");
                
                dt.Rows.Add(dtRow);
            }
            GridView1.DataSource = dt;
            //Session["temptbl"] = dt;
            GridView1.DataBind();
            //dt.AcceptChanges();
            


                TextBox src = ((TextBox)sender);
            src.Text = "2000";
            
            ////GridViewRow row = (GridViewRow)src.Parent.Parent;
            //foreach(GridViewRow row in GridView1.Rows)
            //{
            //    ((TextBox)row.FindControl("txtExtraPayment")).Text = "df";
            //}

        }
        // actualNoOfPay = fn_ActualPayments();

        //while (Convert.ToDecimal(remoFirstChar(dt.Rows[count]["ExtraPayment"].ToString())) > 0)
        //{
        //    sumOptionalPayment = sumOptionalPayment + Convert.ToDecimal(remoFirstChar(dt.Rows[count]["ExtraPayment"].ToString())); 
        //    totalInterest = totalInterest + Convert.ToDecimal(remoFirstChar(dt.Rows[count]["interest"].ToString())); 
        //}

        //if (scheduledNumberOfPayment != actualNoOfPay)
        //{

        //    NoOfPaySaved = fn_PaymentsSaved(Convert.ToInt32(scheduledNumberOfPayment) , Convert.ToInt32(txtActualNumberOfPayments.Text)); 
        //    txtNumberOfPaymentsSaved.Text = NoOfPaySaved.ToString("C");

        //    dollarAmountOfPaySaved = fn_DollarAmountOfPaySaved();  
        //    txtDollarAmountOfPaymentsSaved.Text = dollarAmountOfPaySaved.ToString("C");

        //   // totalEarlyPayments = fn_TotalOfEarlyPay();
        //   // NoOfYearsSaved = Convert.ToInt32(dollarAmountOfPaySaved / totalEarlyPayments);
        //   // txtNumberOfYearsSaved.Text = NoOfYearsSaved.ToString();

        //    totalInterestSaved = dollarAmountOfPaySaved - totalEarlyPayments;
        //    txtTotalInterest.Text = totalInterestSaved.ToString("C");
        //}

        //DotNetNuke.Data.DataProvider.Instance().ExecuteNonQuery("sp_insert_LoanCalculator", txtLoanAmount.Text.Trim(), annInterest, loanYears, txtStartDateOfLoan.Text.Trim(), optionalPayment, scheduledMonthlyPayment, scheduledNumberOfPayment,,,,,,,,totalPayment);

    }


Now I am facing the problem is on cheked change event
1) all calculations are performing well at first time event raise but the texbox I inserted value and fire the event get cleared after the postback. since I am not able to calculate it again at second time when I raise the same event for another textbox. So please tell me how to preserve the values of gridview textbox during all the postback caused by checkedchange event.
Tags: C# (C# 4.0), ASP.NET

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900