如何对已动态生成的列中所有行的值求和?

问题描述 投票:0回答:1

早安研究员,

我正在尝试对称为SubTotal的特定列的每一行中的所有值求和SubTotal需要从每行的LineTotal中求和,但是这些行是动态生成的,并且在单击按钮时发生。我将在下面链接我的代码和一个屏幕截图,也许你们中的一个可以帮助我:

foreach (DataRow dataRow in dt.Rows)
{                     
    //Adding dt.Rows to Strings for Use in iTextSharp
    string lineNumberInput = dataRow[1].ToString();
    string itemCodeInput = dataRow[12].ToString();
    string itemNameInput = dataRow[13].ToString();
    string QtyInput = dataRow[14].ToString();
    string UnitPriceInput = dataRow[15].ToString();
    //string Discount = dt.Rows[0][""].ToString();
    string lineTotalInput = dataRow[16].ToString();
    string wasReturnedInput = dataRow[17].ToString();

    //Implementing strings in iTextSharp
    var Cell_LineNumberList = new PdfPCell(new 
    Phrase(lineNumberInput, tablefont));
    var Cell_ItemCodelist = new PdfPCell(new 
    Phrase(itemCodeInput, tablefont));
    var Cell_ItemNamelist = new PdfPCell(new 
    Phrase(itemNameInput, tablefont));
    var Cell_Qtylist = new PdfPCell(new Phrase(QtyInput, 
    tablefont));
    var Cell_UnitPricelist = new PdfPCell(new 
    Phrase(UnitPriceInput, tablefont));
    var Cell_Discountlist = new PdfPCell(new 
    Phrase("None", tablefont));
    var Cell_LineTotallist = new PdfPCell(new 
    Phrase(lineTotalInput, tablefont));
    var Cell_WasReturnedlist = new PdfPCell(new 
    Phrase(wasReturnedInput, tablefont));

    //Aligning all the cells
    Cell_LineNumberList.HorizontalAlignment = 
    Element.ALIGN_CENTER;
    Cell_ItemCodelist.HorizontalAlignment = 
    Element.ALIGN_CENTER;
    Cell_ItemNamelist.HorizontalAlignment = 
    Element.ALIGN_CENTER;
    Cell_Qtylist.HorizontalAlignment = 
    Element.ALIGN_CENTER;
    Cell_UnitPricelist.HorizontalAlignment = 
    Element.ALIGN_CENTER;
    Cell_Discountlist.HorizontalAlignment = 
    Element.ALIGN_CENTER;
    Cell_LineTotallist.HorizontalAlignment = 
    Element.ALIGN_CENTER;
    Cell_WasReturnedlist.HorizontalAlignment = 
    Element.ALIGN_CENTER;


    //adding the cells to the table
    t.AddCell(Cell_LineNumberList);
    t.AddCell(Cell_ItemCodelist);
    t.AddCell(Cell_ItemNamelist);
    t.AddCell(Cell_Qtylist);
    t.AddCell(Cell_UnitPricelist);
    t.AddCell(Cell_Discountlist);
    t.AddCell(Cell_LineTotallist);
    t.AddCell(Cell_WasReturnedlist);
}

下面您将以红色显示我要求和的列的屏幕快照,以绿色显示value(来自这些值的地方)列的屏幕快照*这些都是动态生成的*

enter image description here

[如果您能告诉我如何将其存储在var中,那么我可以从那里拿走它并先谢谢您。

c# sql itext datarow
1个回答
0
投票

尝试如下在您的foreach循环外部使用“ Line Total”列上的LINQ

var subTotal= rows.Sum(row => row.Field<double>("LineTotal"));

或在逐行处理时,使用一种古老的方法,即拥有一个变量并将行值添加到其中。

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.