Gridview中所选项目的总数

时间:2011-03-24 08:11:14

标签: c# .net asp.net gridview calculated-columns

我有一个Gridview

enter image description here

我有点击按钮和两个标签。 (Risk_label和MV_label)

风险和MV栏具有价格价值。

我的复选框列名称为NameCheckBoxField1NameCheckBoxField2

我如何只计算“我在Gridview中选择哪个”我的标签中的风险总额和MV总数?

实施例

Risk (Checked rows) --> 10, 20, 30 ---> Risk_label = 60
MV (Checked rows) --> 20, 30, 40 ---> MV_label = 90

EDİT:我试试这段代码;

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

但是我收到了错误。

2 个答案:

答案 0 :(得分:1)

我认为jQuery对你来说是最好的选择。 1.为Risk_Label和MV_Label添加类 2.在复选框上,单击使用类获取同一行的Risk_Label和MV_Label的值。 3.如果选中,则添加其他值减去值。

    $('.mygrid :checkbox').click(function () {

                            var amt = parseFloat($(this).parents('tr').find('.ClassRisk_label').text());
                            //One Fee Case
                            if (!isNaN(amt)) {
                                if ($(this).is(':checked')) {
                                    totalAmt = totalAmt + amt;
                                }
                                else {
                                    totalAmt = totalAmt - amt;
                                }
                            }
//Show the value...
});

答案 1 :(得分:1)

protected void CalculateButton_Click(object sender, EventArgs e)
        {
            Int32 totalMVValue = 0, totalRiskValue = 0;

            // Iterate through the Products.Rows property
            foreach (GridViewRow row in GridView1.Rows)
            {
                // Access the CheckBox
                CheckBox mvSelectorCheckBox = (CheckBox)row.FindControl("MVSelector");
                if (mvSelectorCheckBox != null && mvSelectorCheckBox.Checked)
                {
                    // First, get the primaryId for the selected row
                    int mvValue=
                        Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
                    totalMVValue += mvValue;
                }

                CheckBox riskSelectorCheckBox = (CheckBox)row.FindControl("RiskSelector");
                if (riskSelectorCheckBox != null && riskSelectorCheckBox.Checked)
                {
                    // First, get the primaryId for the selected row
                    int riskValue =
                        Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
                    totalRiskValue += riskValue;
                }
            }           
        }

查看你的上一条评论:

 <asp:templatefield headertext=""> <itemtemplate> <asp:CheckBox DataField="NameCheckBoxField1" Checked="True" runat="server"></asp:CheckBox> </itemtemplate> </asp:templatefield>

DataField是否分配了NameCheckBoxField1?或者这是一个错字? 它应该是ID="NameCheckBoxField1"

相关问题