从Gridview中获取一个已选中复选框的值

时间:2012-03-21 13:46:43

标签: c# asp.net

我生成的Gridview如下:

<asp:GridView ID="Cash_GridView" runat="server" CssClass="Grid" >
<Columns>
<asp:TemplateField>
     <ItemTemplate>
        <asp:CheckBox ID="MemberCheck" runat="server" />
     </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Loan_Acno" HeaderText="Loan A/C number" />
</Columns>
</asp:Gridview>
<asp:Button ID="CashPayButton" runat="server" Text="Pay Dividend" CssClass="bluesome" OnClick="CashPayButton_Click" />

当我点击特定行上的复选框时,现在还有上面的按钮点击事件我希望整个行在后面的代码中的按钮点击事件中得到计算

protected void CashPayButton_Click(object sender, EventArgs e)
 { }

4 个答案:

答案 0 :(得分:1)

这是你想要的吗?

protected void CashPayButton_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in Cash_GridView.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            CheckBox c = (CheckBox)row.FindControl("MemberCheck");
            if (c.Checked)
            {
                //do calculation with other controls in the row
            }
        }
    }           
}

(或者如果单击复选框立即进行计算,则不会起作用)

答案 1 :(得分:1)

假设这是您必须单击进行计算的唯一按钮,您可以执行以下操作(请注意我正在使用Load事件),当您单击按钮并发生回发时将调用它。

(由于回发而点击按钮时会发生计算)

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            ProcessRows();
        }
    }

    private  void ProcessRows()
    {
        foreach (GridViewRow oneRow in Cash_GridView.Rows)
        {
            CheckBox checkBoxControl = oneRow.FindControl("MemberCheck") as CheckBox;

            if (checkBoxControl != null && checkBoxControl.Checked)
            {
                // You have a row with a 'Checked' checkbox.

                // You can access other controls like I have accessed the checkbox
                // For example, If you have a textbox named "YourTextBox":
                TextBox textBoxSomething = oneRow.FindControl("YourTextBox") as TextBox;
                if (textBoxSomething != null)
                {
                    // Use the control value for whatever purpose you want.
                    // Example:
                    if (!string.IsNullOrWhiteSpace(textBoxSomething.Text))
                    {
                        int amount = 0;
                        int.TryParse(textBoxSomething.Text, out amount);

                        // Now you can use the amount for any calculation
                    }
                }
            }
        }
    }

答案 2 :(得分:0)

使用以下代码:

protected void CashPayButton_Click(object sender, EventArgs e)
{


    foreach(Gridviewrow gvr in Cash_GridView.Rows)
    {
       if(((CheckBox)gvr.findcontrol("MemberCheck")).Checked == true)
       {

          int uPrimaryid= gvr.cells["uPrimaryID"];
       }
    }
}

答案 3 :(得分:0)

        foreach (GridViewRow r in GridView1.Rows)
        {
            if ((r.Cells[2].Controls.OfType<CheckBox>().ToList()[0]).Checked == true)
            {
               //your code.
            }
        }