viernes, 21 de septiembre de 2012

Mostrar total de suma de columnas de Gridview con evento OnBlur y Javascript en ASP.NET

Encontre este truquito navegando un poco por Internet, para esto primero creamos nuestro GridView:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
            onrowdatabound="GridView1_RowDataBound">
        <Columns>        
 <asp:TemplateField HeaderText="col1">
<ItemTemplate>
<asp:TextBox ID="txtcol1" Text='<%#Eval("id1") %>' runat="server">
</asp:TextBox>
 </ItemTemplate>
 </asp:TemplateField> 
  <asp:TemplateField HeaderText="col2">
<ItemTemplate>
<asp:TextBox ID="txtcol2" Text='<%#Eval("id2") %>' runat="server">
</asp:TextBox>
 </ItemTemplate>
 </asp:TemplateField> 
        </Columns>
        </asp:GridView>   
Ahora creamos nuestra funcion JavaScript:
function JvfunonBlur()
    {
      var grid = document.getElementById('<%=GridView1.ClientID %>');
        var col1;
        var totalcol1 = 0;
        var col2;
        var totalcol2 = 0;         
        for (i = 0; i < grid.rows.length; i++) 
        {
            col1 = grid.rows[i].cells[0];
            col2 = grid.rows[i].cells[1];
            
             for (j = 0; j < col1.childNodes.length; j++) 
             {
                if (col1.childNodes[j].type == "text")
                 {
                 if(!isNaN(col1.childNodes[j].value) &&  col1.childNodes[j].value != "")
                     {
                        totalcol1 += parseInt(col1.childNodes[j].value)
                     }
                }
             }            
             for (j = 0; j < col2.childNodes.length; j++)
             {
                if (col2.childNodes[j].type == "text")
                 {
                     if(!isNaN(col2.childNodes[j].value) &&  col2.childNodes[j].value != "")
                     {
                        totalcol2 += parseInt(col2.childNodes[j].value)
                     }
                }
            }
        }
        document.getElementById('<%=txttotal1.ClientID %>').value = totalcol1;
        document.getElementById('<%=txttotal2.ClientID %>').value = totalcol2;
    }   
Llamamos a esta funcion Javascript en el evento RowDataBound en el codigo de C#, aqui abajo veran el codigo completo junto la funcion que llena el Grid en el evento PostBack.
protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FillGrid();
        }
    }
    private void FillGrid()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("id1", typeof(int));
        dt.Columns.Add("id2", typeof(int));
        dt.Rows.Add(0, 0);
        dt.Rows.Add(0, 0);
        GridView1.DataSource = dt;
        GridView1.DataBind();        
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            TextBox txt = (TextBox)e.Row.FindControl("txtcol1");
            txt.Attributes.Add("onBlur", "JvfunonBlur();");
            TextBox txt1 = (TextBox)e.Row.FindControl("txtcol2");
            txt1.Attributes.Add("onBlur", "JvfunonBlur();");
        }
    }
}
Bueno si prefieren pegar el codigo de uno solo aqui esta para la parte .aspx:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function JvfunonBlur()
    {
      var grid = document.getElementById('<%=GridView1.ClientID %>');
        var col1;
        var totalcol1 = 0;
        var col2;
        var totalcol2 = 0;         
        for (i = 0; i < grid.rows.length; i++) 
        {
            col1 = grid.rows[i].cells[0];
            col2 = grid.rows[i].cells[1];
            
             for (j = 0; j < col1.childNodes.length; j++) 
             {
                if (col1.childNodes[j].type == "text")
                 {
                 if(!isNaN(col1.childNodes[j].value) &&  col1.childNodes[j].value != "")
                     {
                        totalcol1 += parseInt(col1.childNodes[j].value)
                     }
                }
             }            
             for (j = 0; j < col2.childNodes.length; j++)
             {
                if (col2.childNodes[j].type == "text")
                 {
                     if(!isNaN(col2.childNodes[j].value) &&  col2.childNodes[j].value != "")
                     {
                        totalcol2 += parseInt(col2.childNodes[j].value)
                     }
                }
            }
        }
        document.getElementById('<%=txttotal1.ClientID %>').value = totalcol1;
        document.getElementById('<%=txttotal2.ClientID %>').value = totalcol2;
    }   
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>    
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>  
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>    
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
            onrowdatabound="GridView1_RowDataBound">
        <Columns>        
 <asp:TemplateField HeaderText="col1">
<ItemTemplate>
<asp:TextBox ID="txtcol1" Text='<%#Eval("id1") %>' runat="server">
</asp:TextBox>
 </ItemTemplate>
 </asp:TemplateField> 
  <asp:TemplateField HeaderText="col2">
<ItemTemplate>
<asp:TextBox ID="txtcol2" Text='<%#Eval("id2") %>' runat="server">
</asp:TextBox>
 </ItemTemplate>
 </asp:TemplateField> 
        </Columns>
        </asp:GridView>       
        Total
         <br />
        <asp:TextBox ID="txttotal1" runat="server"></asp:TextBox>
        <asp:TextBox ID="txttotal2" runat="server"></asp:TextBox>
        <br />        
    </ContentTemplate>
    </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

1 comentario: