在选择复选框时,将gridview列的值相加

时间:2012-10-22 04:17:10

标签: c# asp.net gridview

我有一个价格列,显示已检查行的总价格。最初我尝试使用选择按钮执行此操作,但它不起作用,因此,我在gridview中添加了一个复选框。现在我需要当我检查一些行时,这些行的总和出现在标签上我厌倦了这段代码,但是我收到了一个错误:

    double sum = 0;

    foreach (GridViewRow gvr in GridView1.Rows)
    {  
        CheckBox cb = (CheckBox)gvr.FindControl("Checkbox1"); 
        if (cb.Checked)
        {
            double amount = Convert.ToDouble(gvr.Cells[2].Text);
            sum += amount;
        }


        Label1.Text = sum.ToString();

    }

2 个答案:

答案 0 :(得分:0)

我假设您正在网格之外完成所有这些工作,我的意思是您在页面上有一个按钮,点击您运行此代码的位置。对???如果是,那么你必须在你的代码中再包含一件事,那就是检查datarow ......

double sum = 0;

foreach (GridViewRow gvr in GridView1.Rows)
{  
 if(gvr.RowType == DataControlRowType.DataRow)
 {
    CheckBox cb = (CheckBox)gvr.FindControl("Checkbox1"); 
    if (cb.Checked)
    {
        //check wether the cell value is empty or not, if empty take a 0 instead...
        double amount = gvr.Cells[2].Text.Trim() != null && gvr.Cells[2].Text.Length>0 ? Convert.ToDouble(gvr.Cells[2].Text.Trim()) : 0;
        sum += amount;
    }


    Label1.Text = sum.ToString();
  }

}

如果不是这种情况,则必须在每个复选框的Change事件上执行此操作。 如果问题得到解决,请通知我,我会帮助你......

答案 1 :(得分:0)

double sum = 0;

foreach (GridViewRow gvr in GridView1.Rows)
{  
    CheckBox cb = (CheckBox)gvr.FindControl("Checkbox1"); 
    if (cb.Checked)
    {
        double amount = Convert.ToDouble(gvr.Cells[2].Text.replace("&nbsp",""));
        sum += amount;
    }


    Label1.Text = sum.ToString();

}