locked
Multiplying two gridview colums to get the third column in a gridview RRS feed

  • Question

  • User1173249824 posted

    Hello, I have been trying to multiply two columns in my gridview to give the total, but I have not been able to have a breakthrough here is my Gridview and what I have Tried

        <asp:GridView ID="GridView1" runat="server" Width="550px"
                                AutoGenerateColumns="false" Font-Names="Arial"
                               AllowPaging="true" ShowFooter="true"
                                OnPageIndexChanging="OnPaging" OnRowEditing="EditCustomer"
                                OnRowUpdating="UpdateCustomer" OnRowCancelingEdit="CancelEdit"
                                PageSize="10" OnRowDataBound="GridView1_RowDataBound">
                                <Columns>
                                    <asp:TemplateField ItemStyle-Width="100px" HeaderText="ItemName">
                                        <ItemTemplate>
                                            <asp:Label ID="txtItemsName" runat="server"
                                                Text='<%# Eval("ItemsName")%>'></asp:Label>
                                        </ItemTemplate>
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txtItemsName" runat="server"
                                                Text='<%# Eval("ItemsName")%>'></asp:TextBox>
                                        </EditItemTemplate>
                                        <FooterTemplate>
                                            <asp:TextBox ID="txtItemsName" runat="server"></asp:TextBox>
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField ItemStyle-Width="100px" HeaderText="Price">
                                        <ItemTemplate>
                                            <asp:Label ID="lblPrice" runat="server"
                                                Text='<%# Eval("Price")%>'></asp:Label>
                                        </ItemTemplate>
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txtPrice" runat="server"
                                                Text='<%# Eval("Price")%>'></asp:TextBox>
                                        </EditItemTemplate>
                                        <FooterTemplate>
                                            <asp:TextBox ID="txtPrice" runat="server"></asp:TextBox>
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField ItemStyle-Width="150px" HeaderText="Qty">
                                        <ItemTemplate>
                                            <asp:Label ID="lblQty" runat="server"
                                                Text='<%# Eval("Qty")%>'></asp:Label>
                                        </ItemTemplate>
                                        <EditItemTemplate>
                                            <asp:TextBox ID="txtQty" runat="server" Text='<%# Eval("Qty")%>'></asp:TextBox>
                                        </EditItemTemplate>
                                        <FooterTemplate>
                                            <asp:TextBox ID="txtQty" AutoPostBack="true" OnTextChanged="txtQty_TextChanged" runat="server"></asp:TextBox>
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    
                                     <asp:TemplateField ItemStyle-Width="100px" HeaderText="Total">
                                        <ItemTemplate>
                                            <asp:TextBox Text="0" ID="txttTotal" runat="server"></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:LinkButton ID="lnkRemove" runat="server"
                                                CommandArgument='<%# Eval("ItemsName")%>' OnClientClick="return confirm('Do you want to delete?')" Text="Delete" OnClick="DeleteCustomer"></asp:LinkButton>
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <asp:Button ID="btnAdd" runat="server" Text="Add"
                                                OnClick="AddNewCustomer" />
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    <asp:CommandField ShowEditButton="True" />
                                </Columns>
                                <AlternatingRowStyle BackColor="#C2D69B" />
                            </asp:GridView>

    Here is what I have tried

     protected void txtQty_TextChanged(object sender, EventArgs e)
        {
    
            TextBox txtPrice = (TextBox)GridView1.Rows[((sender as TextBox).NamingContainer as GridViewRow).RowIndex].Cells[1].FindControl("txtPrice");
          TextBox txtQty = (TextBox)GridView1.Rows[((sender as TextBox).NamingContainer as GridViewRow).RowIndex].Cells[2].FindControl("txtQty");
          TextBox txtTotal = (TextBox)GridView1.Rows[((sender as TextBox).NamingContainer as GridViewRow).RowIndex].Cells[3].FindControl("txtTtotal");
         txtTotal.Text = (decimal.Parse(txtPrice.Text) * (decimal.Parse(txtQty.Text))).ToString();
    
        }

    It returs this error: Index was out of range. Must be non-negative and less than the size of the collection.

    Please Can I get a solution to it here

    Thanks

    Saturday, December 3, 2016 3:29 PM

Answers

  • User283571144 posted

    Hi Alamdreal1,

    Hello, I have been trying to multiply two columns in my gridview to give the total, but I have not been able to have a breakthrough here is my Gridview and what I have Tried

    According to your description and code, I couldn't understand clearly about your requirement now.

    Do you mean you want to show the total result in the third textbox named "txttTotal"?

    If this is your requirement, I suggest you could firstly add the footertemplate in the Total column, then you could use GridView1.FooterRow.FindControl method to find the textbox.

    At last you could get the value and multiply.

    More details, you could refer to follow codes:

      <asp:GridView ID="GridView1" runat="server" Width="550px"
                    AutoGenerateColumns="false" Font-Names="Arial"
                     ShowFooter="true"
                      
                     >
                    <Columns>
                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="ItemName">
                            <ItemTemplate>
                                <asp:Label ID="txtItemsName" runat="server"
                                    Text='<%# Eval("ItemsName")%>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="txtItemsName" runat="server"
                                    Text='<%# Eval("ItemsName")%>'></asp:TextBox>
                            </EditItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtItemsName" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Price">
                            <ItemTemplate>
                                <asp:Label ID="lblPrice" runat="server"
                                    Text='<%# Eval("Price")%>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="txtPrice" runat="server"
                                    Text='<%# Eval("Price")%>'></asp:TextBox>
                            </EditItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtPrice" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField ItemStyle-Width="150px" HeaderText="Qty">
                            <ItemTemplate>
                                <asp:Label ID="lblQty" runat="server"
                                    Text='<%# Eval("Qty")%>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="txtQty" runat="server" Text='<%# Eval("Qty")%>'></asp:TextBox>
                            </EditItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtQty" AutoPostBack="true" OnTextChanged="txtQty_TextChanged" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
    
                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Total">
                            <ItemTemplate>
                                <asp:TextBox Text="0" ID="txttTotal" runat="server"></asp:TextBox>
                            </ItemTemplate>
                                <FooterTemplate>
                                <asp:TextBox ID="txttTotal" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkRemove" runat="server"
                                    CommandArgument='<%# Eval("ItemsName")%>' OnClientClick="return confirm('Do you want to delete?')" Text="Delete" OnClick="lnkRemove_Click"></asp:LinkButton>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:Button ID="btnAdd" runat="server" Text="Add"
                                    OnClick="btnAdd_Click"/>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:CommandField ShowEditButton="True" />
                    </Columns>
                    <AlternatingRowStyle BackColor="#C2D69B" />
                </asp:GridView>

    Code-behind:

     protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable d1 = new DataTable();
                    d1.Columns.Add("ItemsName");
                    d1.Columns.Add("Price");
                    d1.Columns.Add("Qty");
                    d1.Rows.Add("1", "360", "3");
                    d1.Rows.Add("1", "370", "4");
                    GridView1.DataSource = d1;
                    GridView1.DataBind();
                }
            }
    
            protected void txtQty_TextChanged(object sender, EventArgs e)
            {
    
                string price = (GridView1.FooterRow.FindControl("txtPrice") as TextBox).Text;
                string qty = (GridView1.FooterRow.FindControl("txtQty") as TextBox).Text;
                string re = ((decimal.Parse(price)) * (decimal.Parse(qty))).ToString();
                (GridView1.FooterRow.FindControl("txttTotal") as TextBox).Text = re;
            }

    Result:

    Besides, if you want to know how to multiply all the column, I suggest you could foreach the gridview or use OnRowDataBound method to get each row's value and multiply.

    More details. you could refer to follow codes:

      protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Label txtPrice = e.Row.FindControl("lblPrice") as Label;
                    Label txtqty = e.Row.FindControl("lblQty") as Label;
                    string re = ((decimal.Parse(txtPrice.Text)) * (decimal.Parse(txtqty.Text))).ToString();
                    TextBox txttot = e.Row.FindControl("txttTotal") as TextBox;
                    txttot.Text = re;
                }
            }

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 5, 2016 6:21 AM
  • User283571144 posted

    Hi  Alamdreal1,

    I have been having problem summing up the Price column to a textbox

    As far as I know, if you convert the gridview row to ItemTemplate, it will convert the bind field to label.

    So you will not find the value by cell.text.

    I suggest you could use GridView1.Rows[i].FindControl method to get the price text.

    More details, you could refer to follow codes:

       protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable d1 = new DataTable();
                    d1.Columns.Add("ItemsName");
                    d1.Columns.Add("Price");
                    d1.Columns.Add("Qty");
                    d1.Rows.Add("njdnvjdn", "2.00", "3");
                    d1.Rows.Add("kxmck mxkl", "4.00", "3");
                    d1.Rows.Add("askcmlkmc", "3.00", "2");
                    d1.Rows.Add("xjzxnjk", "4.00", "5");
                    GridView1.DataSource = d1;
                    GridView1.DataBind();
                    sumTotal();
                }
            }
    
            void sumTotal()
            {
                //   Control control = null;
                decimal sum = 0;
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    Label txtPrice = GridView1.Rows[i].FindControl("lblPrice") as Label;
                    string ss = txtPrice.Text;
                    sum += Convert.ToDecimal(ss); //set a break point to check the cell value.
                }
                txtAmnt.Text = sum.ToString();
            }

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 5, 2016 9:49 AM
  • User283571144 posted

    Hi Alamdreal1,

    I want the total to add up on the button click

    According to your description and code, do you mean you want to show the total result after you add the data into database?

    If this is your requirement, I suggest you could call CalcutateTheSum method after GridView1.DataBind method.

    Because GridView1.DataBind will rebuild the gridview.

    More details, you could refer to follow codes:

    protected void AddNewCustomer(object sender, EventArgs e)
        {
            CalcutateTheSum();
    
            string CustName = txtCust.Text;
            string TransId = txtTrans.Text;
            string Staff = txtSName.Text;
            decimal Tamount = Convert.ToDecimal(((TextBox)GridView1.FooterRow.FindControl("txtTotal")).Text);
            DateTime dta = Convert.ToDateTime(txtTDate.Text);
            string ItemsName = ((TextBox)GridView1.FooterRow.FindControl("txtItemsName")).Text;
            decimal Price = Convert.ToDecimal(((TextBox)GridView1.FooterRow.FindControl("txtPrice")).Text);
            string Quantity = ((TextBox)GridView1.FooterRow.FindControl("txtQty")).Text;
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into [Transaction]([CustomerName],[TransactionNo],[StaffName],[ItemsName], [Price], [Qty], [Tamount],TransactionDate) " +
            "values(@1,@2,@3,@ItemsName, @Price, @Qty,@4,@5);" +
            "select ItemsName,Price,Qty,Tamount from [Transaction] where TransactionNo = '" + TransId + "'";
            cmd.Parameters.Add("@1", SqlDbType.NVarChar).Value = CustName;
            cmd.Parameters.Add("@2", SqlDbType.NVarChar).Value = TransId;
            cmd.Parameters.Add("@3", SqlDbType.NVarChar).Value = Staff;
            cmd.Parameters.Add("@4", SqlDbType.Decimal).Value = Tamount;
            cmd.Parameters.Add("@5", SqlDbType.DateTime).Value = dta;
            cmd.Parameters.Add("@ItemsName", SqlDbType.VarChar).Value = ItemsName;
            cmd.Parameters.Add("@Price", SqlDbType.Decimal).Value = Price;
            cmd.Parameters.Add("@Qty", SqlDbType.VarChar).Value = Quantity;
            GridView1.DataSource = GetData(cmd);
            GridView1.DataBind();
            CalcutateTheSum();
    
        }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 6, 2016 11:19 AM
  • User283571144 posted

    Hi Alamdreal1,

    Thanks so much but here is the error am getting again

    According to your codes, I found you sum the lblTotal's value.

    Could you please post total gridview and the method in code-behind now?

    As far as I know this error means, the txtPrice.Text value couldn't be converted to Decimal value.

    The txtPrice.Text value may be null or letter.

    So I suggest you could use VS debugger to check it firstly.

    Then I suggest you could try to use decimal.TryParse method to check the txtPrice.Text could be converted to Decimal.

    More details, you could refer to follow codes:

       void sumTotal()
            {
                //   Control control = null;
                decimal sum = 0;
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    decimal resu = 0;
                    Label txtPrice = GridView1.Rows[i].FindControl("lblTotal") as Label;
                    string ss = txtPrice.Text;
                    if (decimal.TryParse(ss, out resu))
                    {
                        sum += resu;
                    }
                }
                txtAmnt.Text = sum.ToString();
            }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 7, 2016 8:42 AM

All replies

  • User475983607 posted

    Do the multiplication in the SQL query that produces the result set.  Then all you have to do bind the grid.

    Saturday, December 3, 2016 7:20 PM
  • User283571144 posted

    Hi Alamdreal1,

    Hello, I have been trying to multiply two columns in my gridview to give the total, but I have not been able to have a breakthrough here is my Gridview and what I have Tried

    According to your description and code, I couldn't understand clearly about your requirement now.

    Do you mean you want to show the total result in the third textbox named "txttTotal"?

    If this is your requirement, I suggest you could firstly add the footertemplate in the Total column, then you could use GridView1.FooterRow.FindControl method to find the textbox.

    At last you could get the value and multiply.

    More details, you could refer to follow codes:

      <asp:GridView ID="GridView1" runat="server" Width="550px"
                    AutoGenerateColumns="false" Font-Names="Arial"
                     ShowFooter="true"
                      
                     >
                    <Columns>
                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="ItemName">
                            <ItemTemplate>
                                <asp:Label ID="txtItemsName" runat="server"
                                    Text='<%# Eval("ItemsName")%>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="txtItemsName" runat="server"
                                    Text='<%# Eval("ItemsName")%>'></asp:TextBox>
                            </EditItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtItemsName" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Price">
                            <ItemTemplate>
                                <asp:Label ID="lblPrice" runat="server"
                                    Text='<%# Eval("Price")%>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="txtPrice" runat="server"
                                    Text='<%# Eval("Price")%>'></asp:TextBox>
                            </EditItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtPrice" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField ItemStyle-Width="150px" HeaderText="Qty">
                            <ItemTemplate>
                                <asp:Label ID="lblQty" runat="server"
                                    Text='<%# Eval("Qty")%>'></asp:Label>
                            </ItemTemplate>
                            <EditItemTemplate>
                                <asp:TextBox ID="txtQty" runat="server" Text='<%# Eval("Qty")%>'></asp:TextBox>
                            </EditItemTemplate>
                            <FooterTemplate>
                                <asp:TextBox ID="txtQty" AutoPostBack="true" OnTextChanged="txtQty_TextChanged" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
    
                        <asp:TemplateField ItemStyle-Width="100px" HeaderText="Total">
                            <ItemTemplate>
                                <asp:TextBox Text="0" ID="txttTotal" runat="server"></asp:TextBox>
                            </ItemTemplate>
                                <FooterTemplate>
                                <asp:TextBox ID="txttTotal" runat="server"></asp:TextBox>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkRemove" runat="server"
                                    CommandArgument='<%# Eval("ItemsName")%>' OnClientClick="return confirm('Do you want to delete?')" Text="Delete" OnClick="lnkRemove_Click"></asp:LinkButton>
                            </ItemTemplate>
                            <FooterTemplate>
                                <asp:Button ID="btnAdd" runat="server" Text="Add"
                                    OnClick="btnAdd_Click"/>
                            </FooterTemplate>
                        </asp:TemplateField>
                        <asp:CommandField ShowEditButton="True" />
                    </Columns>
                    <AlternatingRowStyle BackColor="#C2D69B" />
                </asp:GridView>

    Code-behind:

     protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable d1 = new DataTable();
                    d1.Columns.Add("ItemsName");
                    d1.Columns.Add("Price");
                    d1.Columns.Add("Qty");
                    d1.Rows.Add("1", "360", "3");
                    d1.Rows.Add("1", "370", "4");
                    GridView1.DataSource = d1;
                    GridView1.DataBind();
                }
            }
    
            protected void txtQty_TextChanged(object sender, EventArgs e)
            {
    
                string price = (GridView1.FooterRow.FindControl("txtPrice") as TextBox).Text;
                string qty = (GridView1.FooterRow.FindControl("txtQty") as TextBox).Text;
                string re = ((decimal.Parse(price)) * (decimal.Parse(qty))).ToString();
                (GridView1.FooterRow.FindControl("txttTotal") as TextBox).Text = re;
            }

    Result:

    Besides, if you want to know how to multiply all the column, I suggest you could foreach the gridview or use OnRowDataBound method to get each row's value and multiply.

    More details. you could refer to follow codes:

      protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Label txtPrice = e.Row.FindControl("lblPrice") as Label;
                    Label txtqty = e.Row.FindControl("lblQty") as Label;
                    string re = ((decimal.Parse(txtPrice.Text)) * (decimal.Parse(txtqty.Text))).ToString();
                    TextBox txttot = e.Row.FindControl("txttTotal") as TextBox;
                    txttot.Text = re;
                }
            }

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 5, 2016 6:21 AM
  • User1173249824 posted

    Thanks so much @Brando ZWZ It worked like a margic,

    I have been having problem summing up the Price column to a textbox

    Here is what I have tried

      protected void Page_Load(object sender, EventArgs e)
    
        {
            if (!IsPostBack)
            {
               
                autoincTransact();
                DataTable d1 = new DataTable();
                d1.Columns.Add("ItemsName");
                d1.Columns.Add("Price");
                d1.Columns.Add("Qty");
                d1.Rows.Add("njdnvjdn", "2.00", "3");
                d1.Rows.Add("kxmck mxkl", "4.00", "3");
                d1.Rows.Add("askcmlkmc", "3.00", "2");
                d1.Rows.Add("xjzxnjk", "4.00", "5");
                GridView1.DataSource = d1;
                GridView1.DataBind();
                sumTotal();
               
            }
        }
    
     void sumTotal()
        {
         //   Control control = null;
            decimal sum = 0;
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                string price = (GridView1.FooterRow.FindControl("txtPrice") as TextBox).Text;
                sum += Convert.ToDecimal(GridView1.Rows[i].Cells[1].Text); //set a break point to check the cell value.
    
            }
            txtAmnt.Text = sum.ToString();
        }


     Here is the error

    Server Error in '/' Application.


    Input string was not in a correct format.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.FormatException: Input string was not in a correct format.

    Source Error: 

    Line 178:        {
    Line 179:            string price = (GridView1.FooterRow.FindControl("txtPrice") as TextBox).Text;
    Line 180:            sum += Convert.ToDecimal(GridView1.Rows[i].Cells[1].Text); //set a break point to check the cell value.
    Line 181:
    Line 182:        }


    Source File: c:\Users\user\Documents\Visual Studio 2012\WebSites\WebTrial1\alam.aspx.cs    Line: 180 

    please all help will be rally appreciated.

    Thanks

    Monday, December 5, 2016 8:37 AM
  • User283571144 posted

    Hi  Alamdreal1,

    I have been having problem summing up the Price column to a textbox

    As far as I know, if you convert the gridview row to ItemTemplate, it will convert the bind field to label.

    So you will not find the value by cell.text.

    I suggest you could use GridView1.Rows[i].FindControl method to get the price text.

    More details, you could refer to follow codes:

       protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    DataTable d1 = new DataTable();
                    d1.Columns.Add("ItemsName");
                    d1.Columns.Add("Price");
                    d1.Columns.Add("Qty");
                    d1.Rows.Add("njdnvjdn", "2.00", "3");
                    d1.Rows.Add("kxmck mxkl", "4.00", "3");
                    d1.Rows.Add("askcmlkmc", "3.00", "2");
                    d1.Rows.Add("xjzxnjk", "4.00", "5");
                    GridView1.DataSource = d1;
                    GridView1.DataBind();
                    sumTotal();
                }
            }
    
            void sumTotal()
            {
                //   Control control = null;
                decimal sum = 0;
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    Label txtPrice = GridView1.Rows[i].FindControl("lblPrice") as Label;
                    string ss = txtPrice.Text;
                    sum += Convert.ToDecimal(ss); //set a break point to check the cell value.
                }
                txtAmnt.Text = sum.ToString();
            }

    Result:

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, December 5, 2016 9:49 AM
  • User1173249824 posted

    Thanks @ Brando zwz. The solutions work perfectly but it is not displaying in my text box

    here is my code

        protected void AddNewCustomer(object sender, EventArgs e)
        {
            CalcutateTheSum()
    
            string CustName = txtCust.Text;
            string TransId = txtTrans.Text;
            string Staff = txtSName.Text;
            decimal Tamount = Convert.ToDecimal(((TextBox)GridView1.FooterRow.FindControl("txtTotal")).Text);
            DateTime dta = Convert.ToDateTime(txtTDate.Text);
            string ItemsName = ((TextBox)GridView1.FooterRow.FindControl("txtItemsName")).Text;
            decimal Price = Convert.ToDecimal(((TextBox)GridView1.FooterRow.FindControl("txtPrice")).Text);
            string Quantity = ((TextBox)GridView1.FooterRow.FindControl("txtQty")).Text;
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into [Transaction]([CustomerName],[TransactionNo],[StaffName],[ItemsName], [Price], [Qty], [Tamount],TransactionDate) " +
            "values(@1,@2,@3,@ItemsName, @Price, @Qty,@4,@5);" +
            "select ItemsName,Price,Qty,Tamount from [Transaction] where TransactionNo = '" + TransId + "'";
            cmd.Parameters.Add("@1", SqlDbType.NVarChar).Value = CustName;
            cmd.Parameters.Add("@2", SqlDbType.NVarChar).Value = TransId;
            cmd.Parameters.Add("@3", SqlDbType.NVarChar).Value = Staff;
            cmd.Parameters.Add("@4", SqlDbType.Decimal).Value = Tamount;
            cmd.Parameters.Add("@5", SqlDbType.DateTime).Value = dta;
            cmd.Parameters.Add("@ItemsName", SqlDbType.VarChar).Value = ItemsName;
            cmd.Parameters.Add("@Price", SqlDbType.Decimal).Value = Price;
            cmd.Parameters.Add("@Qty", SqlDbType.VarChar).Value = Quantity;
            GridView1.DataSource = GetData(cmd);
            GridView1.DataBind();
    
    
        }
     void CalcutateTheSum()
        {
         
            decimal sum = 0;
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                Label txtPrice = GridView1.Rows[i].FindControl("lblTotal") as Label;
                string ss = txtPrice.Text;
                sum += Convert.ToDecimal(ss);
            }
            txtAmt.Text = sum.ToString();
          
        }

    I want the total to add up on the button click

    Thanks for the help

    Tuesday, December 6, 2016 9:04 AM
  • User283571144 posted

    Hi Alamdreal1,

    I want the total to add up on the button click

    According to your description and code, do you mean you want to show the total result after you add the data into database?

    If this is your requirement, I suggest you could call CalcutateTheSum method after GridView1.DataBind method.

    Because GridView1.DataBind will rebuild the gridview.

    More details, you could refer to follow codes:

    protected void AddNewCustomer(object sender, EventArgs e)
        {
            CalcutateTheSum();
    
            string CustName = txtCust.Text;
            string TransId = txtTrans.Text;
            string Staff = txtSName.Text;
            decimal Tamount = Convert.ToDecimal(((TextBox)GridView1.FooterRow.FindControl("txtTotal")).Text);
            DateTime dta = Convert.ToDateTime(txtTDate.Text);
            string ItemsName = ((TextBox)GridView1.FooterRow.FindControl("txtItemsName")).Text;
            decimal Price = Convert.ToDecimal(((TextBox)GridView1.FooterRow.FindControl("txtPrice")).Text);
            string Quantity = ((TextBox)GridView1.FooterRow.FindControl("txtQty")).Text;
            SqlConnection con = new SqlConnection(ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "insert into [Transaction]([CustomerName],[TransactionNo],[StaffName],[ItemsName], [Price], [Qty], [Tamount],TransactionDate) " +
            "values(@1,@2,@3,@ItemsName, @Price, @Qty,@4,@5);" +
            "select ItemsName,Price,Qty,Tamount from [Transaction] where TransactionNo = '" + TransId + "'";
            cmd.Parameters.Add("@1", SqlDbType.NVarChar).Value = CustName;
            cmd.Parameters.Add("@2", SqlDbType.NVarChar).Value = TransId;
            cmd.Parameters.Add("@3", SqlDbType.NVarChar).Value = Staff;
            cmd.Parameters.Add("@4", SqlDbType.Decimal).Value = Tamount;
            cmd.Parameters.Add("@5", SqlDbType.DateTime).Value = dta;
            cmd.Parameters.Add("@ItemsName", SqlDbType.VarChar).Value = ItemsName;
            cmd.Parameters.Add("@Price", SqlDbType.Decimal).Value = Price;
            cmd.Parameters.Add("@Qty", SqlDbType.VarChar).Value = Quantity;
            GridView1.DataSource = GetData(cmd);
            GridView1.DataBind();
            CalcutateTheSum();
    
        }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, December 6, 2016 11:19 AM
  • User1173249824 posted

    Thanks so much but here is the error am getting again

    Server Error in '/' Application.


    Input string was not in a correct format.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.FormatException: Input string was not in a correct format.

    Source Error: 

    Line 192:            Label txtPrice = GridView1.Rows[i].FindControl("lblTotal") as Label;
    Line 193:            string ss = txtPrice.Text;
    Line 194:            sum += Convert.ToDecimal(ss);
    Line 195:        }
    Line 196:        txtAmt.Text = Convert.ToString(sum);

    Thanks for all the help 

    Server Er

    ror in '/' Application.


    Input string was not in a correct format.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

    Exception Details: System.FormatException: Input string was not in a correct format.

    Source Error: 

    Line 192:            Label txtPrice = GridView1.Rows[i].FindControl("lblTotal") as Label;
    Line 193:            string ss = txtPrice.Text;
    Line 194:            sum += Convert.ToDecimal(ss);
    Line 195:        }
    Line 196:        txtAmt.Text = Convert.ToString(sum);
    Tuesday, December 6, 2016 2:55 PM
  • User283571144 posted

    Hi Alamdreal1,

    Thanks so much but here is the error am getting again

    According to your codes, I found you sum the lblTotal's value.

    Could you please post total gridview and the method in code-behind now?

    As far as I know this error means, the txtPrice.Text value couldn't be converted to Decimal value.

    The txtPrice.Text value may be null or letter.

    So I suggest you could use VS debugger to check it firstly.

    Then I suggest you could try to use decimal.TryParse method to check the txtPrice.Text could be converted to Decimal.

    More details, you could refer to follow codes:

       void sumTotal()
            {
                //   Control control = null;
                decimal sum = 0;
                for (int i = 0; i < GridView1.Rows.Count; i++)
                {
                    decimal resu = 0;
                    Label txtPrice = GridView1.Rows[i].FindControl("lblTotal") as Label;
                    string ss = txtPrice.Text;
                    if (decimal.TryParse(ss, out resu))
                    {
                        sum += resu;
                    }
                }
                txtAmnt.Text = sum.ToString();
            }

    Best Regards,

    Brando

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, December 7, 2016 8:42 AM