使用Javascript的多列动态gridview的列和

时间:2016-09-25 12:06:54

标签: javascript c# asp.net gridview

我有一个Dynamic asp Gridview,所有列都作为模板feild TextBox。 Gridview的列也是动态的,列数可能每次都有所不同。

请在下面找到代码

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;
    }
}

为了获得行总数,我在keydown事件中添加了一个Javascript函数,并且它的工作清晰

 //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();         

   }

结果如下 enter image description here

任何人都可以帮我找出每列的总和(所有相同的cssclass)。并将其显示在Sizetotal行中,因为我无法遍历列

3 个答案:

答案 0 :(得分:1)

有一种非常简单的方法。

为每个列添加页脚和标签,然后从数据库端进行最佳计算是使用LINQ和分组依据,找到每个列的页脚标签控件并将值绑定到这些页脚的标签控件,这样就是UI将减少负担。

请参阅此处了解代码:

网格中的

.ASPX页面:

  <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#代码:

 var searchResult = soService.SearchResult(companyId);
            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);
            }

答案 1 :(得分:1)

不确定您的要求,但这可能对您有所帮助,将数据绑定到网格后,再次遍历列列表

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");
} 

答案 2 :(得分:1)

我会通过html5 data attributes为每个文本框提供行ID和列ID。并在javascript(jQuery)中通过列id过滤文本框。

示例:

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

顺便说一下,使用jQuery。太棒了。