locked
Column (Debit and Credit ) total of footer is not displaying ,when adding row in gridview? RRS feed

  • Question

  • User-367318540 posted

    when i am adding rows into gridview then debit and credit column total is not getting display ,i also applied another condition on textbox of gridview (txtdebit and txtcredit) ,that when i input value in debit ,then credit textbox enable will be false, and same for credit textbox

    below is my html

    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" />
        <script src="Scripts/jquery-3.4.1.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $(".js-example-placeholder-single").select2({
                    placeholder: "Select",
                    allowClear: true
                });
            });
            $(function () {
                $("[id*=txtDebit]").change(function () {
                    var grandTotal = 0;
                    $("[id*=txtDebit]").each(function () {
                        console.log(this);
                         grandTotal += parseFloat($(this).val()||0);
                    });
    
                    $("[id*=lblTotal]").text("Total:" + grandTotal.toString());
                })
                });
                  $(function () {
                $("[id*=txtCredit]").change(function () {
                    var grandTotal = 0;
                    $("[id*=txtCredit]").each(function () {
                        console.log(this);
                         grandTotal += parseFloat($(this).val()||0);
                    });
    
                    $("[id*=lblTotal2]").text("Total:" + grandTotal.toString());
                })
    
    
            });
    
        </script>
    
    
    
        <table class="nav-justified">
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td style="width: 756px">&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td style="width: 756px">&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td style="width: 756px">&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td style="width: 756px">&nbsp;</td>
                <td>
                    <asp:Button ID="btn_add" runat="server" Text="Add" OnClick="btn_add_Click" Width="66px" />
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td colspan="2" rowspan="5">
    
        <asp:GridView ID="gvtrans" runat="server" AllowSorting="True" AutoGenerateColumns="False" CssClass="active right"
        BorderColor="#E7E7FF" itemstyle-wrap="True" GridLines="Horizontal" ShowHeaderWhenEmpty="True"  OnRowDataBound="gvtrans_RowDataBound"
        ShowFooter="True" OnRowCreated="gvtrans_RowCreated" BackColor="White" BorderStyle="None" BorderWidth="1px" CellPadding="3" style="margin-top: 0px; margin-left: 0px;" Width="824px">
        <AlternatingRowStyle CssClass="altrowstyle" BackColor="#F7F7F7" />
                        <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
        <HeaderStyle CssClass="headerstyle" BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
                        <PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
        <RowStyle CssClass="rowstyle" BackColor="#E7E7FF" ForeColor="#4A3C8C" />
        <Columns>
              <asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
            <asp:TemplateField HeaderText="Code">
                <ItemTemplate>
                    <asp:TextBox ID="txtcode" runat="server"></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Head">
                <ItemTemplate>
                    <asp:Label ID="lbfourdr" runat="server" Visible="false" />
                    <asp:DropDownList runat="server" AutoPostBack="true" CssClass="form-control js-example-placeholder-single" ID="ddlfourdr" Width="250px" OnSelectedIndexChanged="ddlfourdr_SelectedIndexChanged">
                    </asp:DropDownList>
                </ItemTemplate>
            </asp:TemplateField>
              
              <asp:TemplateField HeaderText="Debit">
                <ItemTemplate>
                    <asp:TextBox ID="txtDebit" runat="server" AutoPostBack="true" OnTextChanged="txtDebit_TextChanged"  ></asp:TextBox>
                </ItemTemplate>                  <FooterTemplate>
                                            <asp:Label ID="lblTotal" runat="server"></asp:Label>
                                        </FooterTemplate>
              
            </asp:TemplateField>
              <asp:TemplateField HeaderText="Credit">
                <ItemTemplate>
                    <asp:TextBox ID="txtCredit" runat="server" AutoPostBack="true" OnTextChanged="txtCredit_TextChanged" ></asp:TextBox>
                </ItemTemplate>
                           <FooterTemplate>
                                            <asp:Label ID="lblTotal2" runat="server"></asp:Label>
                                        </FooterTemplate>
            </asp:TemplateField>
             <asp:TemplateField HeaderText="Type">
                                    <ItemTemplate>
                                        <asp:DropDownList ID="ddltype" runat="server" Width="70px">
                                            <asp:ListItem Text="Credit" Value="1"></asp:ListItem>
                                            <asp:ListItem Text="Debit" Value="2"></asp:ListItem>
                                        </asp:DropDownList>
                                    </ItemTemplate>
                                </asp:TemplateField>
        </Columns>
                        <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
                        <SortedAscendingCellStyle BackColor="#F4F4FD" />
                        <SortedAscendingHeaderStyle BackColor="#5A4C9D" />
                        <SortedDescendingCellStyle BackColor="#D8D8F0" />
                        <SortedDescendingHeaderStyle BackColor="#3E3277" />
    </asp:GridView>
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td style="width: 217px" class="modal-sm">&nbsp;</td>
                <td style="width: 756px">&nbsp;</td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
    </asp:Content>

    C#

    SqlConnection con = new SqlConnection("Data Source=SERVER1\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=WHMS;MultipleActiveResultSets=True;");
            DataTable dt = new DataTable();
            DataRow dr = null;
            protected void Page_Load(object sender, EventArgs e)
            {
    
                if (!Page.IsPostBack)
                {
                    SetInitialRow();
                }
       }
    
            private void SetInitialRow()
            {
              
                dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
                dt.Columns.Add(new DataColumn("txtcode", typeof(string)));
                dt.Columns.Add(new DataColumn("ddlfourdr", typeof(string)));
                dt.Columns.Add(new DataColumn("txtDebit", typeof(string)));
                dt.Columns.Add(new DataColumn("txtCredit", typeof(string)));
                dt.Columns.Add(new DataColumn("ddltype", typeof(string)));
                dr = dt.NewRow();
                dr["RowNumber"] = 1;
                dr["txtcode"] = String.Empty;
                dr["txtDebit"] = String.Empty;
                dr["txtCredit"] = String.Empty;
                dt.Rows.Add(dr);
                ViewState["CurrentTable"] = dt;
                gvtrans.DataSource = dt;
                gvtrans.DataBind();
            }
        
    
            protected void gvtrans_RowCreated(object sender, GridViewRowEventArgs e)
            {
    
            }
    
            protected void gvtrans_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
    
                    TextBox txtcrcode = (TextBox)e.Row.FindControl("txtcodedr");
                    DropDownList ddlContnam = (DropDownList)e.Row.FindControl("ddlfourdr");
                    SqlCommand cmd = new SqlCommand("select *  from tbl_Account_L_Four ", con);
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    
                    DataTable dt = new DataTable();
    
                    sda.Fill(dt);
                    ddlContnam.DataSource = dt;
                    ddlContnam.DataTextField = "Level_Four_Name";
                    ddlContnam.DataValueField = "Level_Four_ID";
    
                    ddlContnam.DataBind();
    
                    ddlContnam.Items.Insert(0, new ListItem("--Select Debit--", "0"));
                }
            }
    
    
            protected void ddlfourdr_SelectedIndexChanged(object sender, EventArgs e)
            {
                DropDownList ddlfourdr = (DropDownList)sender;
                GridViewRow row = (GridViewRow)ddlfourdr.NamingContainer;
                DropDownList ddlModel = (DropDownList)row.FindControl("ddlfourdr");
                TextBox txtcodedr = (TextBox)row.FindControl("txtcode");
    
    
    
                String strQuery = "select Level_Four_ID from tbl_Account_L_Four where" +
                           " Level_Four_ID = @Level_Four_ID";
    
                SqlCommand cmd = new SqlCommand();
                cmd.Parameters.AddWithValue("@Level_Four_ID", ddlModel.SelectedValue);
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strQuery;
                cmd.Connection = con;
                try
                {
                    con.Open();
                    SqlDataReader sdr = cmd.ExecuteReader();
                    while (sdr.Read())
                    {
                        txtcodedr.Text = sdr[0].ToString();
    
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    con.Close();
                    con.Dispose();
                }
            }
            protected void txtDebit_TextChanged(object sender, EventArgs e)
            {
                decimal total = 0;
                foreach (GridViewRow row in gvtrans.Rows)
                {
                    TextBox Debits = row.FindControl("txtDebit") as TextBox;
                    TextBox Credits = row.FindControl("txtCredit") as TextBox;
                    DropDownList ddl = row.FindControl("ddltype") as DropDownList;
    
                    ddl.ClearSelection();
                    if (Debits.Text != "")
                    {
                        ddl.Items.FindByText("Debit").Selected = true;
                        Credits.Enabled = false;
                    }
                  //  total += Convert.ToDecimal(Debits.Text);
    
                }
    
      //(gvtrans.FooterRow.FindControl("lblTotal") as Label).Text = total.ToString("N2");
    
            }      protected void txtCredit_TextChanged(object sender, EventArgs e)
            {
                decimal total = 0;
                foreach (GridViewRow row in gvtrans.Rows)
                {
                    TextBox Debits = row.FindControl("txtDebit") as TextBox;
                    TextBox Credits = row.FindControl("txtCredit") as TextBox;
    
                    DropDownList ddl = row.FindControl("ddltype") as DropDownList;
    
                    ddl.ClearSelection();
                    if (Credits.Text != "")
                    {
                        ddl.Items.FindByText("Credit").Selected = true;
                        Debits.Enabled = false;
                    }
                 //   total += Convert.ToDecimal(Credits.Text);
    
                }
    
               // (gvtrans.FooterRow.FindControl("lblTotalcr") as Label).Text = total.ToString("N2");
    
            }
    
            protected void btn_add_Click(object sender, EventArgs e)
            {
                int rowIndex = 0;
    
    
    
                if (ViewState["CurrentTable"] != null)
    
                {
    
                    DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
    
                    DataRow drCurrentRow = null;
    
                    if (dtCurrentTable.Rows.Count > 0)
    
                    {
    
                        for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
    
                        {
    
                            //extract the TextBox values
    
                            TextBox box1 = (TextBox)gvtrans.Rows[rowIndex].Cells[1].FindControl("txtcode");
    
                            DropDownList box2 = (DropDownList)gvtrans.Rows[rowIndex].Cells[2].FindControl("ddlfourdr");
    
                            TextBox box3 = (TextBox)gvtrans.Rows[rowIndex].Cells[3].FindControl("txtDebit");
                            TextBox box4 = (TextBox)gvtrans.Rows[rowIndex].Cells[4].FindControl("txtCredit");
                            DropDownList box5 = (DropDownList)gvtrans.Rows[rowIndex].Cells[5].FindControl("ddlType");
    
                            drCurrentRow = dtCurrentTable.NewRow();
    
                            drCurrentRow["RowNumber"] = i + 1;
    
    
    
                            dtCurrentTable.Rows[i - 1]["txtcode"] = box1.Text;
    
                            dtCurrentTable.Rows[i - 1]["ddlfourdr"] = box2.Text;
    
                            dtCurrentTable.Rows[i - 1]["txtDebit"] = box3.Text;
    
                            dtCurrentTable.Rows[i - 1]["txtCredit"] = box4.Text;
    
                            dtCurrentTable.Rows[i - 1]["ddlType"] = box5.Text;
    
    
    
                            rowIndex++;
    
                        }
    
                        dtCurrentTable.Rows.Add(drCurrentRow);
    
                        ViewState["CurrentTable"] = dtCurrentTable;
    
    
    
                        gvtrans.DataSource = dtCurrentTable;
    
                        gvtrans.DataBind();
    
                    }
    
                }
    
                else
    
                {
    
                    Response.Write("ViewState is null");
    
                }
    
    
    
                //Set Previous Data on Postbacks
    
                SetPreviousData();
            }
    
            private void SetPreviousData()
            {
                int rowIndex = 0;
    
                if (ViewState["CurrentTable"] != null)
    
                {
    
                    DataTable dt = (DataTable)ViewState["CurrentTable"];
    
                    if (dt.Rows.Count > 0)
    
                    {
    
                        for (int i = 0; i < dt.Rows.Count; i++)
    
                        {
    
    
                            TextBox box1 = (TextBox)gvtrans.Rows[rowIndex].Cells[1].FindControl("txtcode");
    
                            DropDownList box2 = (DropDownList)gvtrans.Rows[rowIndex].Cells[2].FindControl("ddlfourdr");
    
                            TextBox box3 = (TextBox)gvtrans.Rows[rowIndex].Cells[3].FindControl("txtDebit");
                            TextBox box4 = (TextBox)gvtrans.Rows[rowIndex].Cells[4].FindControl("txtCredit");
                            DropDownList box5 = (DropDownList)gvtrans.Rows[rowIndex].Cells[5].FindControl("ddlType");
    
    
    
    
                            box1.Text = dt.Rows[i]["txtcode"].ToString();
    
                            box2.Text = dt.Rows[i]["ddlfourdr"].ToString();
    
                            box3.Text = dt.Rows[i]["txtDebit"].ToString();
                            box4.Text = dt.Rows[i]["txtCredit"].ToString();
    
                            box5.Text = dt.Rows[i]["ddlType"].ToString();
    
    
    
                            rowIndex++;
    
                        }
    
                    }
    
                }
            }
        }
    }
        

    Monday, August 3, 2020 11:12 AM

Answers

  • User-939850651 posted

    Hi akhterr,

    I created an example using the code you provided, and the problem you mentioned-the total is not displayed. I think this is caused by the postback generated by the TextBox. At the moment of post back, you should see the total data displayed in the label, but it just flickers and disappears.

    Have you tried other ways to store total data? For example, use Session.

    I made some changes to the code, I don’t know if it meets your expectations:

    protected void gvtrans_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    TextBox txtcrcode = (TextBox)e.Row.FindControl("txtcodedr");
                    DropDownList ddlContnam = (DropDownList)e.Row.FindControl("ddlfourdr");
                    SqlCommand cmd = new SqlCommand("select *  from tbl_Account_L_Four ", con);
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    ddlContnam.DataSource = dt;
                    ddlContnam.DataTextField = "Level_Four_Name";
                    ddlContnam.DataValueField = "Level_Four_ID";
                    ddlContnam.DataBind();
                    ddlContnam.Items.Insert(0, new ListItem("--Select Debit--", "0"));
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    Label label = e.Row.FindControl("lblTotal") as Label;
                    label.Text = Session["DebitTotal"] == null ? "" : Session["DebitTotal"].ToString();
    
                    Label label2 = e.Row.FindControl("lblTotal2") as Label;
                    label2.Text = Session["CreditTotal"] == null ? "" : Session["CreditTotal"].ToString();
                }
            }
    
    protected void txtDebit_TextChanged(object sender, EventArgs e)
            {
                decimal total = 0;
                foreach (GridViewRow row in gvtrans.Rows)
                {
                    TextBox Debits = row.FindControl("txtDebit") as TextBox;
                    TextBox Credits = row.FindControl("txtCredit") as TextBox;
                    DropDownList ddl = row.FindControl("ddltype") as DropDownList;
    
                    ddl.ClearSelection();
                    if (Debits.Text != "")
                    {
                        ddl.Items.FindByText("Debit").Selected = true;
                        Credits.Enabled = false;
                    }
                    total += Convert.ToDecimal(Debits.Text==""?"0": Debits.Text);
                }
                Session["DebitTotal"] = total;
                (gvtrans.FooterRow.FindControl("lblTotal") as Label).Text = total.ToString("N2");
            }
    
    protected void txtCredit_TextChanged(object sender, EventArgs e)
            {
                decimal total = 0;
                foreach (GridViewRow row in gvtrans.Rows)
                {
                    TextBox Debits = row.FindControl("txtDebit") as TextBox;
                    TextBox Credits = row.FindControl("txtCredit") as TextBox;
    
                    DropDownList ddl = row.FindControl("ddltype") as DropDownList;
    
                    ddl.ClearSelection();
                    if (Credits.Text != "")
                    {
                        ddl.Items.FindByText("Credit").Selected = true;
                        Debits.Enabled = false;
                    }
                    total += Convert.ToDecimal(Credits.Text==""?"0": Credits.Text);
                }
                Session["CreditTotal"] = total;
                (gvtrans.FooterRow.FindControl("lblTotal2") as Label).Text = total.ToString("N2");
            }

    Result:

    Hope this can help you.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 14, 2020 7:03 AM

All replies

  • User475983607 posted

    As far as I can tell there is no code that saves the new values.  It is up to you to write this code.

    I strongly recommend dropping the ViewState cache and writing directly to the table.  There are a couple of reasons for approach.  As a general rule of thumb, you should never cache data that changes.  Cache is only efficient for  Also, you are double caching the data source in ViewState.  The Gridview also stores data in ViewState.

    When you have a design like yours, it is far more efficient and cleaner to save the record directly in the database and return a new result set. 

    Monday, August 3, 2020 11:56 AM
  • User-367318540 posted

    Hi mgebhard,

    can you mentioned or correct my code ,as you know that i am not up to your level of thinking.

    Monday, August 3, 2020 11:59 AM
  • User-939850651 posted

    Hi akhterr,

    I created an example using the code you provided, and the problem you mentioned-the total is not displayed. I think this is caused by the postback generated by the TextBox. At the moment of post back, you should see the total data displayed in the label, but it just flickers and disappears.

    Have you tried other ways to store total data? For example, use Session.

    I made some changes to the code, I don’t know if it meets your expectations:

    protected void gvtrans_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    TextBox txtcrcode = (TextBox)e.Row.FindControl("txtcodedr");
                    DropDownList ddlContnam = (DropDownList)e.Row.FindControl("ddlfourdr");
                    SqlCommand cmd = new SqlCommand("select *  from tbl_Account_L_Four ", con);
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    ddlContnam.DataSource = dt;
                    ddlContnam.DataTextField = "Level_Four_Name";
                    ddlContnam.DataValueField = "Level_Four_ID";
                    ddlContnam.DataBind();
                    ddlContnam.Items.Insert(0, new ListItem("--Select Debit--", "0"));
                }
                else if (e.Row.RowType == DataControlRowType.Footer)
                {
                    Label label = e.Row.FindControl("lblTotal") as Label;
                    label.Text = Session["DebitTotal"] == null ? "" : Session["DebitTotal"].ToString();
    
                    Label label2 = e.Row.FindControl("lblTotal2") as Label;
                    label2.Text = Session["CreditTotal"] == null ? "" : Session["CreditTotal"].ToString();
                }
            }
    
    protected void txtDebit_TextChanged(object sender, EventArgs e)
            {
                decimal total = 0;
                foreach (GridViewRow row in gvtrans.Rows)
                {
                    TextBox Debits = row.FindControl("txtDebit") as TextBox;
                    TextBox Credits = row.FindControl("txtCredit") as TextBox;
                    DropDownList ddl = row.FindControl("ddltype") as DropDownList;
    
                    ddl.ClearSelection();
                    if (Debits.Text != "")
                    {
                        ddl.Items.FindByText("Debit").Selected = true;
                        Credits.Enabled = false;
                    }
                    total += Convert.ToDecimal(Debits.Text==""?"0": Debits.Text);
                }
                Session["DebitTotal"] = total;
                (gvtrans.FooterRow.FindControl("lblTotal") as Label).Text = total.ToString("N2");
            }
    
    protected void txtCredit_TextChanged(object sender, EventArgs e)
            {
                decimal total = 0;
                foreach (GridViewRow row in gvtrans.Rows)
                {
                    TextBox Debits = row.FindControl("txtDebit") as TextBox;
                    TextBox Credits = row.FindControl("txtCredit") as TextBox;
    
                    DropDownList ddl = row.FindControl("ddltype") as DropDownList;
    
                    ddl.ClearSelection();
                    if (Credits.Text != "")
                    {
                        ddl.Items.FindByText("Credit").Selected = true;
                        Debits.Enabled = false;
                    }
                    total += Convert.ToDecimal(Credits.Text==""?"0": Credits.Text);
                }
                Session["CreditTotal"] = total;
                (gvtrans.FooterRow.FindControl("lblTotal2") as Label).Text = total.ToString("N2");
            }

    Result:

    Hope this can help you.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 14, 2020 7:03 AM