最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Column sum of multiple columns of dynamic gridview using Javascript - Stack Overflow

programmeradmin0浏览0评论

I have a Dynamic asp Gridview with all columns as template feild TextBox. The columns of the Gridview are also dynamic and column count may vary everytime.

Please find code below

public void FillPoDetails()
{
    DataTable dt = new DataTable();           
    dt = pmdata.createdatatable(int.Parse(Session["OurStyleid"].ToString()), int.Parse(Session["PoPackid"].ToString()));
    GenerateTable(dt.Columns.Count, dt.Rows.Count,dt);
    foreach (DataColumn col in dt.Columns)
    {
        //Declare the bound field and allocate memory for the bound field.
        TemplateField bfield = new TemplateField();

        //Initalize the DataField value.
        bfield.HeaderTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Header, col.ColumnName);

        //Initialize the HeaderText field value.
        bfield.ItemTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Item, col.ColumnName);

        //Add the newly created bound field to the GridView.
        GrdDynamic.Columns.Add(bfield);
    }
    GrdDynamic.DataSource = dt;    
    GrdDynamic.DataBind();  
}
public GridViewTemplate(ListItemType type, string colname)
{
    //Stores the template type.
    _templateType = type;

    //Stores the column name.
    _columnName = colname;
}

void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
    switch (_templateType)
    {
        case ListItemType.Header:
            //Creates a new label control and add it to the container.
            Label lbl = new Label();            
            //Allocates the new label object.
            lbl.Text = _columnName;
            lbl.CssClass = "Headerclass";
            //Assigns the name of the column in the lable.
            container.Controls.Add(lbl);        
            //Adds the newly created label control to the container.
            break;
        case ListItemType.Item:
            //Creates a new text box control and add it to the container.
            TextBox tb1 = new TextBox();                            
            //Allocates the new text box object.
            tb1.DataBinding += new EventHandler(tb1_DataBinding);    
            //Attaches the data binding event.
            tb1.Columns =6;
            //Creates a column with size 4.
            // tb1.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            tb1.Width = 100;
            tb1.Wrap = true;
            tb1.ID = "txt_" + _columnName;
            if(_columnName== "ColorTotal")
            {
                tb1.CssClass = "ColorTotal";
            }
            else if (_columnName == "Color")
            {
                tb1.CssClass = "Color";
            }
            else
            {
                tb1.CssClass = "txtCalQty";
                tb1.Attributes.Add("onkeypress", "return isNumberKey(event,this)");
                tb1.Attributes.Add("onkeyup", "sumofQty(this)");
            }                       
            container.Controls.Add(tb1);                            
            //Adds the newly created textbox to the container.  
            break;
    }
}

And inorder to get the row total I had added a Javascript function on keydown event and its working clearly

 //calculate the sum of qty on keypress
   function sumofQty(objText) {


       var cell = objText.parentNode;

       var row = cell.parentNode;

       var sum = 0;
       var textboxs = row.getElementsByClassName("txtCalQty");

       for (var i = 0; i < textboxs.length; i++)
       {
           sum += parseFloat(textboxs[i].value);
       }
       var textboxtotalqtys = row.getElementsByClassName("ColorTotal");
       textboxtotalqtys[0].value = sum.toString();         

   }

And the result is Like below

can anyone please help me in finding out the sum of each columns(all same cssclass).and display it in the Sizetotal row because I am not able to loop through columns

I have a Dynamic asp Gridview with all columns as template feild TextBox. The columns of the Gridview are also dynamic and column count may vary everytime.

Please find code below

public void FillPoDetails()
{
    DataTable dt = new DataTable();           
    dt = pmdata.createdatatable(int.Parse(Session["OurStyleid"].ToString()), int.Parse(Session["PoPackid"].ToString()));
    GenerateTable(dt.Columns.Count, dt.Rows.Count,dt);
    foreach (DataColumn col in dt.Columns)
    {
        //Declare the bound field and allocate memory for the bound field.
        TemplateField bfield = new TemplateField();

        //Initalize the DataField value.
        bfield.HeaderTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Header, col.ColumnName);

        //Initialize the HeaderText field value.
        bfield.ItemTemplate = new ArtWebApp.Controls.GridViewTemplate(ListItemType.Item, col.ColumnName);

        //Add the newly created bound field to the GridView.
        GrdDynamic.Columns.Add(bfield);
    }
    GrdDynamic.DataSource = dt;    
    GrdDynamic.DataBind();  
}
public GridViewTemplate(ListItemType type, string colname)
{
    //Stores the template type.
    _templateType = type;

    //Stores the column name.
    _columnName = colname;
}

void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
    switch (_templateType)
    {
        case ListItemType.Header:
            //Creates a new label control and add it to the container.
            Label lbl = new Label();            
            //Allocates the new label object.
            lbl.Text = _columnName;
            lbl.CssClass = "Headerclass";
            //Assigns the name of the column in the lable.
            container.Controls.Add(lbl);        
            //Adds the newly created label control to the container.
            break;
        case ListItemType.Item:
            //Creates a new text box control and add it to the container.
            TextBox tb1 = new TextBox();                            
            //Allocates the new text box object.
            tb1.DataBinding += new EventHandler(tb1_DataBinding);    
            //Attaches the data binding event.
            tb1.Columns =6;
            //Creates a column with size 4.
            // tb1.Width = System.Web.UI.WebControls.Unit.Percentage(100);
            tb1.Width = 100;
            tb1.Wrap = true;
            tb1.ID = "txt_" + _columnName;
            if(_columnName== "ColorTotal")
            {
                tb1.CssClass = "ColorTotal";
            }
            else if (_columnName == "Color")
            {
                tb1.CssClass = "Color";
            }
            else
            {
                tb1.CssClass = "txtCalQty";
                tb1.Attributes.Add("onkeypress", "return isNumberKey(event,this)");
                tb1.Attributes.Add("onkeyup", "sumofQty(this)");
            }                       
            container.Controls.Add(tb1);                            
            //Adds the newly created textbox to the container.  
            break;
    }
}

And inorder to get the row total I had added a Javascript function on keydown event and its working clearly

 //calculate the sum of qty on keypress
   function sumofQty(objText) {


       var cell = objText.parentNode;

       var row = cell.parentNode;

       var sum = 0;
       var textboxs = row.getElementsByClassName("txtCalQty");

       for (var i = 0; i < textboxs.length; i++)
       {
           sum += parseFloat(textboxs[i].value);
       }
       var textboxtotalqtys = row.getElementsByClassName("ColorTotal");
       textboxtotalqtys[0].value = sum.toString();         

   }

And the result is Like below

can anyone please help me in finding out the sum of each columns(all same cssclass).and display it in the Sizetotal row because I am not able to loop through columns

Share Improve this question edited Oct 2, 2016 at 6:19 Imran Sh 1,7964 gold badges30 silver badges54 bronze badges asked Sep 25, 2016 at 12:06 Sreenath GangaSreenath Ganga 7364 gold badges20 silver badges50 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 1 +50

I would give every textbox a row id and a column id through html5 data attributes. and in javascript (jQuery) filter the textboxes through column id.

example:

..
var sum = 0;
$( "input[data-column-id='" + selectedColumnId + "']" ).each(function( index )
{ 
   sum += parseFloat($( this ).val() );
});
..

By the way, use jQuery. its amazing.

Not sure about your requirement but this may help you, After binding data to grid, once again loop through the column list

GrdDynamic.DataSource = dt;    
GrdDynamic.DataBind();
int rowIndex=2;
GrdDynamic.FooterRow.Cells[1].Text = "Total";
GrdDynamic.FooterRow.Cells[1].HorizontalAlign = HorizontalAlign.Right;
foreach (DataColumn col in dt.Columns)
{
   decimal total = dt.AsEnumerable().Sum(row => row.Field<decimal>(col.Caption));
   GrdDynamic.FooterRow.Cells[rowIndex++].Text = total.ToString("N2");
} 

There is a very simple way.

Add Footer and Label to each Column, Then do calculations from database side best is use LINQ and Group by, find footer Label Controls for each column and Bind values to those Footer's Label Control, in this way your UI will have less load.

See here for code:

.ASPX Page in Grid:

  <asp:TemplateField HeaderText="Total">
   <ItemTemplate>
  <asp:Literal ID="ltrlTotal" Text='<%#Eval("Total") %>' runat="server"> </asp:Literal> // For Sub Total
</ItemTemplate>
 <FooterTemplate>
 <strong><asp:Literal ID="ltrlGrandTotal" runat="server"> // This is Grand Total
  </asp:Literal></strong>
 </FooterTemplate>                       
 </asp:TemplateField>

C# Code:

 var searchResult = soService.SearchResult(panyId);
            var grandTotal = searchResult.Select(so => so.Total).Sum();
            searchResult.All(aa => aa.GrandTotal == grandTotal);

            gridSo.DataSource = searchResult;
            gridSo.DataBind();

            if (searchResult.Count > 0)
            {
                Literal ltrlGrandTotal = gridSo.FooterRow.FindControl("ltrlGrandTotal") as Literal;
                if (ltrlGrandTotal != null)
                    ltrlGrandTotal.Text = string.Format("Grand Total : $ {0}", grandTotal);
            }
发布评论

评论列表(0)

  1. 暂无评论