0

我有一个价格列,显示选中行的总价格。最初我尝试使用选择按钮执行此操作,但没有成功,因此,我在 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();

    }
4

2 回答 2

0

我假设您在网格之外进行所有这些工作,我的意思是您在页面上的某个位置通过单击运行此代码的某个按钮。正确的???如果是,那么您必须在代码中再包含一件事,那就是检查数据行...

双倍总和 = 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 事件中执行此操作。如果解决了问题,请告诉我问题,我很乐意为您提供帮助...

于 2012-10-22T05:13:13.297 回答
0

双倍总和 = 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();

}
于 2012-10-22T05:37:24.520 回答