2012-02-15 62 views
0

我在网格视图中有一个“时间长度”列,我希望在C#中总结该特定列,并发布总时间标签名为总时间。我怎样才能做到这一点?总结GridView列值

示例代码:

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(); 
+2

什么样的GridView的(WPF,HTML, Winforms)给定的代码有什么问题?您需要为每行获取列值和总和而不是每列。 – CodingBarfield 2012-02-15 15:03:42

+2

@Coding:假设winforms是因为SelectedColumns属性(添加标签) – 2012-02-15 15:08:20

回答

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

似乎真的!这有什么问题吗?

+0

我试过上面的代码..但是我得到的结果是“0”,是的,它是一个窗体,我觉得这是通过数据绑定完成,但不知道如何......任何人都可以帮助解决这个问题。 – user1100199 2012-02-15 15:56:37

+0

你的专栏的索引是什么?它真的是1吗? 1表示第二列! – mrbm 2012-02-15 17:00:12

+0

哇有一个很大的错误! dgTestSteps.SelectedColumns.Count是不正确的使用dgTestSteps.Rows.Count – mrbm 2012-02-15 17:01:24

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是局部的,但你可以很容易地格式它没有使用资源。

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

我想这正好起来并且没有问题