2013-12-20 47 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,而不是使用小数浮动。它为我工作。