locked
Adding/Subtracting 1 from a label control text value in a gridview RRS feed

  • Question

  • User-1633045945 posted

    Hi all,

    I have a gridview with a label control that shows the count of an item (lblcount) 

    There are two button a btnsubtract_one and a btnadd_one on either side of the label control.

    I cannot figure out the jquery to add/subtract 1 to the label.text value when the btnadd_one/btnsubtract_one onclientclick event is triggered.

    Pure novice with jquery so any help is greatly appreciated.

    Thank you

    Saturday, May 7, 2016 11:42 PM

Answers

  • User-1633045945 posted

    Thank you for the response. I figured it out with the following code:

    This is in the code behind:

    Protected Sub gvitems_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs)
    
    If e.Row.RowType = DataControlRowType.DataRow Then
    Dim hf As HiddenField = DirectCast(e.Row.FindControl("hfsetquantity"), HiddenField)
    
    Dim lb_ As LinkButton = e.Row.FindControl("lbaddcount")
    Dim lbsub As LinkButton = e.Row.FindControl("lbsubtractcount")
    Dim t As TextBox = e.Row.FindControl("lblcount")
    
    ' t.Text = hf.Value
    lb_.OnClientClick = "javascript:add1(""" & t.ClientID.ToString & """,""" & hf.ClientID & """); return false;"
    lbsub.OnClientClick = "javascript:subtract1(""" & t.ClientID.ToString & """,""" & hf.ClientID & """); return false;"
    
    
    
    End If
    
    End Sub

    and the jquery script

    <script type="text/javascript">
    function add1(t,h) {

    var _t = "#" + t;
    var _h = "#" + h;

    var i = $(_t).val();
    i = parseInt(i) + 1;
    //alert(i);
    $(_t).val(i);
    // $(_h).val(i);


    if ($(_t).val() != $(_h).val()) {

    $(_t).css({ 'background-color': '#f00' });
    $(_t).css({ 'color': '#fff' });
    } else {


    $(_t).css({ 'background-color': 'transparent' });
    $(_t).css({ 'color': 'inherit' });
    }



    };

    function subtract1(t,h) {

    //t is the textbox to add1 or subtract 1 from the current text value

    //h is the hiddenfield containing the number of items that is supposed to be in t

    // if t != h then the background and font changes.


    var _t = "#" + t;
    var _h = "#" + h;

    var i = $(_t).val();

    // alert(_h);

    if (parseInt(i) != 0) {
    i = parseInt(i) - 1;

    }

    $(_t).val(i);


    if ($(_t).val() != $(_h).val()) {
    $(_t).css({ 'background-color': '#f00' });
    $(_t).css({ 'color': '#fff' });
    } else {

    $(_t).css({ 'background-color': 'transparent' });
    $(_t).css({ 'color': 'inherit' });
    }

    };

    </script>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 10, 2016 1:55 AM

All replies

  • User475983607 posted

    There are quite a few tutorials that describe how to do update a GridView.  Here's one form MSDN that uses the command name and value. 

    https://msdn.microsoft.com/en-us/library/bb907626.aspx

    A GridView is a data control whcih is bound to a data source.  You must update the data source then rebind the GridView to see the update.  Being that we have no idea what the data source is and no source code, it's a bit difficult to accurately answer this question.  The source code helps us to understand the design and we can better provide a solution that fits the design.

    I put together a basic example.  the data source is mocked and stored in ViewState.  Clicking the buttons will increment and decrement each label.  Refresh the page to start over. Use the Visual studio debugger to step through the code.

    Markup

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo3.aspx.cs" Inherits="TestingWeb.GridViewDemo3" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
                
        </div><asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
                <Columns>
                    <asp:TemplateField HeaderText="Item">
                        <ItemTemplate>
                            <asp:Button ID="btnsubtract_on" runat="server" Text="Subtract One" CommandName="Subtract" CommandArgument='<%# Bind("Id") %>' OnClick="btnsubtract_on_Click" />
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("Count") %>'></asp:Label>
                            <asp:Button ID="btnadd_one" runat="server" Text="Add One"  CommandName="Add" CommandArgument='<%# Bind("Id") %>' OnClick="btnadd_one_Click" />
                            </ItemTemplate>
                   </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </form>
    </body>
    </html>
    

    Code

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace TestingWeb
    {
        public partial class GridViewDemo3 : System.Web.UI.Page
        {
            public List<DataItem> MyData
            {
                get 
                {
                    if (ViewState["MyData"] == null)
                    {
                        PopulateData();
                    }
                    return (List<DataItem>)ViewState["MyData"];
                }
                set {
                    ViewState["MyData"] = value;
                }
    
            }
            protected void Page_Load(object sender, EventArgs e)
            {
                if(!Page.IsPostBack)
                {
                    BindGridView();
                }
            }
    
            protected void BindGridView()
            {
                GridView1.DataSource = MyData;
                GridView1.DataBind();
            }
    
            protected void btnsubtract_on_Click(object sender, EventArgs e)
            {
                Button subtract = (Button)sender;
                int id = 0;
                int.TryParse(subtract.CommandArgument, out id);
    
                List<DataItem> data = MyData;
                DataItem item = data.Where(m => m.Id == id).FirstOrDefault();
                item.Count--;
                BindGridView();
            }
    
            protected void btnadd_one_Click(object sender, EventArgs e)
            {
                Button add = (Button)sender;
                int id = 0;
                int.TryParse(add.CommandArgument, out id);
    
                List<DataItem> data = MyData;
                DataItem item = data.Where(m => m.Id == id).FirstOrDefault();
                item.Count++;
                BindGridView();
            }
    
            protected void PopulateData()
            {
                List<DataItem> data = new List<DataItem>();
    
                for (int i = 0; i < 5; i++)
                {
                    data.Add(new DataItem() { Id = i, Count = 0 });
                }
    
                MyData = data;
            }
    
    
        }
    
        [Serializable]
        public class DataItem {
            public int Id { get; set; }
            public int Count { get; set; }
        }
    }

    Sunday, May 8, 2016 12:39 PM
  • User61956409 posted

    Hi mstrsftwr,

    You could refer to the following sample code to access value from label and do calculation.

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label ID="lblcount" runat="server" Text='<%#Eval("count") %>'></asp:Label>
                    <asp:Button ID="btnsubtract_one" runat="server" Text="subtract" OnClientClick="return subtractone(this);" />
                    <asp:Button ID="btnadd_one" runat="server" Text="add" OnClientClick="return addone(this);" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    
    <script>
        function subtractone(obj) {
            var count = $(obj).parent().find("span[id*='lblcount']").text();
            //alert(count);
            var newcount = parseFloat(count) - 1;
            $(obj).parent().find("span[id*='lblcount']").text(newcount);
            return false;
    
        }
    
        function addone(obj) {
            var count = $(obj).parent().find("span[id*='lblcount']").text();
            //alert(count);
            var newcount = parseFloat(count) + 1;
            $(obj).parent().find("span[id*='lblcount']").text(newcount);
            return false;
        }
    </script>
    

    Best Regards,

    Fei Han



    Monday, May 9, 2016 9:35 AM
  • User-1633045945 posted

    Thank you for the response. I figured it out with the following code:

    This is in the code behind:

    Protected Sub gvitems_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs)
    
    If e.Row.RowType = DataControlRowType.DataRow Then
    Dim hf As HiddenField = DirectCast(e.Row.FindControl("hfsetquantity"), HiddenField)
    
    Dim lb_ As LinkButton = e.Row.FindControl("lbaddcount")
    Dim lbsub As LinkButton = e.Row.FindControl("lbsubtractcount")
    Dim t As TextBox = e.Row.FindControl("lblcount")
    
    ' t.Text = hf.Value
    lb_.OnClientClick = "javascript:add1(""" & t.ClientID.ToString & """,""" & hf.ClientID & """); return false;"
    lbsub.OnClientClick = "javascript:subtract1(""" & t.ClientID.ToString & """,""" & hf.ClientID & """); return false;"
    
    
    
    End If
    
    End Sub

    and the jquery script

    <script type="text/javascript">
    function add1(t,h) {

    var _t = "#" + t;
    var _h = "#" + h;

    var i = $(_t).val();
    i = parseInt(i) + 1;
    //alert(i);
    $(_t).val(i);
    // $(_h).val(i);


    if ($(_t).val() != $(_h).val()) {

    $(_t).css({ 'background-color': '#f00' });
    $(_t).css({ 'color': '#fff' });
    } else {


    $(_t).css({ 'background-color': 'transparent' });
    $(_t).css({ 'color': 'inherit' });
    }



    };

    function subtract1(t,h) {

    //t is the textbox to add1 or subtract 1 from the current text value

    //h is the hiddenfield containing the number of items that is supposed to be in t

    // if t != h then the background and font changes.


    var _t = "#" + t;
    var _h = "#" + h;

    var i = $(_t).val();

    // alert(_h);

    if (parseInt(i) != 0) {
    i = parseInt(i) - 1;

    }

    $(_t).val(i);


    if ($(_t).val() != $(_h).val()) {
    $(_t).css({ 'background-color': '#f00' });
    $(_t).css({ 'color': '#fff' });
    } else {

    $(_t).css({ 'background-color': 'transparent' });
    $(_t).css({ 'color': 'inherit' });
    }

    };

    </script>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, May 10, 2016 1:55 AM