2013-12-20 46 views
0

我想統計GridView總數,我的for循環出了什麼問題?如何計算gridview單元格

public void Bind() 
{ 
    //Assign the datasource to GridView 
    this.grdCart.DataSource = Get_Arealist(); 
    //Databind the grid 
    this.grdCart.DataBind();  

    decimal a = 0, c = 0; 
    for (int i = 0; i <= (grdCart.Rows.Count); i++) 
    { 
     a = Convert.ToDecimal(grdCart.Rows[i].Cells[3].Text.ToString()); 
     c = c + a; //storing total qty into variable 
     c++; 
    } 
    Label2.Text = c.ToString(); 
} 
+0

什麼總數?你想要4rth列中所有單元格的數字總和嗎? –

+0

如果我改變int它也不工作,雅我想總結4rth列 – Mickey

+1

你不想要C++ – NoChance

回答

1

一個簡單的變化可以調整c = c + ac += a但是這不是你的問題。試圖改變代碼作爲這樣:

public void Bind() 
{ 
    //Assign the datasource to GridView 
    this.grdCart.DataSource = Get_Arealist(); 
    //Databind the grid 
    this.grdCart.DataBind(); 


    decimal a = 0, c = 0; 
    for (int i = 0; i < grdCart.RowCount; i++) 
    { 
     a = Convert.ToDecimal(grdCart.Rows[i].Cells[3].Text.ToString()); 
     c += a; //storing total qty into variable 
    } 
    Label2.Text = Convert.ToString(c); 
} 
+0

錯誤出來,索引超出範圍 – Mickey

+0

索引超出範圍。必須是非負數且小於集合的大小。 參數名稱:index – Mickey

+0

<= if chg to Mickey

-1

試試這個:

decimal c = 0; decimal a = 0; 
      for (int i = 0; i <= grdCart.Rows.Count-1; i++) 
      { 
          a = Convert.ToDecimal(grdCart.Rows[i].Cells[3].Text); 
          c=c+a; 

      } 
+0

不知道y和wht我錯了得到的結果是0. – Mickey

+0

您可以跟蹤變量(a)中的值是否爲至少1個非零的單元格? – NoChance

0
decimal total = 0D; 
for (int i = 0; i < grdCart.Rows.Count; ++i) 
{ 
    total += Convert.ToDecimal(grdCart.Rows[i].Cells[3].Value); 
} 
Label2.Text = total.ToString(); 
+0

不知道y和wht我錯了得到的結果是0 – Mickey

+0

你可以檢查grdCart.Rows [i] .Cells [3] .Value,看看它是否抓取細胞的實際值。單元格是否包含文本或控件? –

+0

無法使用.value它顯示錯誤 – Mickey

0

@ Ksdevc或者可以是如果犯規初始化變量c爲0,而不是使用小數浮動。它爲我工作。