int sum = 0;
            for (int i = 0; i < dataGridView2.Rows.Count;i++ )
            {
                sum +=Convert.ToInt32 ( dataGridView2.Rows[i].Cells[2].Value.ToString());
               
               
            } 
             label11.Text= sum.ToString();
错误:未将对象引用设置到对象的实例
有正确的方法吗?
datagridview中的数据是根据我点击范围后得到的。每点击一次就变一次,想求每次这列的和且显示到label上

解决方案 »

  1.   

    Rows[i].Cells[2].Value,这里面的三个对象,自己检查,有null值,估计是value为null,无法转换,你做一下判断吧
      

  2.   

    默认是从0列开始。看看你的价格在哪列上。如果价格在第三列就 Rows[i].Cells[2].Value 在其他就得改cells[里面的值]
      

  3.   

    在datagridview中,价格是第3列啊。
      

  4.   

    建议在里面GridView1_RowDataBound写
    protected int Sum=0;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
      {//合计
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
      DataRowView myrows = (DataRowView)e.Row.DataItem;
      sum += Convert.ToDouble(myrows[6].ToString());
      }
      if (e.Row.RowType == DataControlRowType.Footer)
      {
      e.Row.Cells[4].Text = "合计金额:";
      e.Row.Cells[5].Text = sum.ToString();
      }
      }
     <FooterTemplate>
         合计:<asp:Label ID="Label1" runat="server" Text='<%# Sum %>' />
      </FooterTemplate>
    参考 http://hi.baidu.com/leilongbing/item/4acadb5b13eec90fe7c4a5c1
      

  5.   

    如果在Button2_Click里面写的话
    sum += Convert.ToInt32(GridView1.Rows[i].Cells[2].Value.ToString());
    ==》改成
    sum += Convert.ToInt32(GridView1.Rows[i].Cells[2].Text.ToString());