求和GridView列值

时间:2012-02-15 15:02:26

标签: c# winforms

我在网格视图中有一个“持续时间”列,我希望在C#中对该特定列求和,并发布在名为Total Time的标签上花费的总时间。我怎么能这样做?

示例代码:

int sum = 0;
for (int i = 0; i < dgTestSteps.SelectedColumns.Count; ++i)
{
    sum += Convert.ToInt32(dgTestSteps.SelectedColumns.Count.ToString());
    //sum += Convert.ToInt32(dgTestSteps.Rows[i].Cells[1].Value);
}
lblTotalTime.Text = sum.ToString();

3 个答案:

答案 0 :(得分:0)

    int sum = 0;
    for (int i = 0; i < dgTestSteps.Rows.Count; ++i)
    {
       sum += Int.Parse(dgTestSteps.Rows[i].Cells[1].Value.ToString());
    }
    lblTotalTime.Text = sum.To String();

看来是真的!这有什么问题吗?

答案 1 :(得分:0)

我这样做是通过聚合类变量中的列行值来实现的:

代码背后:

        protected void ItemsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // Get the row variable values
            var rowView = (DataRowView)e.Row.DataItem;
            var itemId = Convert.ToInt32(rowView["ItemID"]);
            var skuId = Convert.ToInt32(rowView["ItemSkuID"]);
            var quantity = Convert.ToInt32(rowView["Quantity"]);

            // Instantiate instances of the relevant classes
            var item = new Item(itemId);
            var sku = new Sku(skuId);

            var itemPrice = String.Format("{0:n2}", (item.Price + sku.PriceAdj));

            var itemPriceLiteral = (Literal)e.Row.FindControl("ItemPrice");
            if (itemPriceLiteral != null)
            {
                itemPriceLiteral.Text = itemPrice;
            }
            var itemExtendedPriceLiteral = (Literal)e.Row.FindControl("ItemExtendedPrice");
            if (itemExtendedPriceLiteral != null)
            {
                var extendedPrice = price * quantity;
                itemExtendedPriceLiteral.Text = String.Format("{0:n2}", extendedPrice);

                // Increment the extended price
                _totalExtendedPrice += extendedPrice;
            }
        }
    } 
    // Lots of stuff omitted from this method for clarity
    public void GetSummary()
    {
        // Set the text property of the total literal below the GridView
        OrderTotal.Text = string.Format((HttpUtility.HtmlDecode(
            (string)GetGlobalResourceObject("ShopStrings", "UsdPrice"))),
                                                        _totalExtendedPrice);
    }

OrderTotal.Text已本地化,但您可以在不使用资源的情况下轻松对其进行格式化。

答案 2 :(得分:0)

您可以使用此功能,但您应该知道列数以0开头并以1

结束
int sum = 0;
        for (int i = 0; i < dgTestSteps.Rows.Count; ++i)
        {
            sum += Convert.ToInt32(dgTestSteps.Rows[i].Cells[0].Value);

        }
        lblTotalTime.Text = sum.ToString();

我试过这个并没有问题