2012-02-15 64 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(); 

我想這正好起來並且沒有問題