Rj Sunny Rj Sunny - 3 months ago 11
ASP.NET (C#) Question

Get checkbox value in grid view instead of using foreach loop

I am using foreach loop to get value of checkbox from a grid view and update the records by geting the current user

regID
on checkbox
CheckedChanged
event.

In ASPX

<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="cbPaid" runat="server" AutoPostBack="true" OnCheckedChanged="cbPaid_CheckedChanged" Checked='<%# bool.Parse(Eval("status").ToString() == "Paid" ? "True": "False") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>


And in
aspx.cs


protected void cbPaid_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in GdParticipants.Rows)
{
CheckBox cbPaid = (CheckBox)row.FindControl("cbPaid");

if (cbPaid!=null && cbPaid.Checked == true)
{
string status = "Paid";
int amount = Convert.ToInt32(ViewState["EventFee"]);
DateTime date = DateTime.Now;
string user = Session["user_id"].ToString();
string regID = row.Cells[2].Text;

string type = "Deposit";
string account = "Participation";
int balance = BAL.fetch_availableBalance();
int total_balance = amount + balance;
string detail = "Participant: "+regID+" fee has been Recieved";
BAL.updateParticipants(regID, status, amount, user, date);
BAL.saveBudgetTracking(type,account,amount,0,total_balance,detail,date);

}
}
Response.Redirect("~/show_members.aspx");
}


The problem with this approach is whenever a new user updated a new record by checking a check box it will loop through the whole records and update the current change all over the previous records.

Anyone please guide me how can I get only the current regID from the row on which the checkbox was being checked and the checkbox value on
checkbox-CheckedChanged
event, instead of a loop?

Answer

The sender is the CheckBox object and it's level 2 partent is the GridViewRow :

protected void cbPaid_CheckedChanged(object sender, EventArgs e)
{
    CheckBox cbPaid = sender as CheckBox;

    if (cbPaid != null && cbPaid.Parent != null)
    {
        GridViewRow row = cbPaid.Parent.Parent as GridViewRow;

        if (row != null )
        {
            string status = "Paid";
            int amount = Convert.ToInt32(ViewState["EventFee"]);
            DateTime date = DateTime.Now;
            string user = Session["user_id"].ToString();
            string regID = row.Cells[2].Text;

            string type = "Deposit";
            string account = "Participation";
            int balance = BAL.fetch_availableBalance();
            int total_balance = amount + balance;
            string detail = "Participant: " + regID + " fee has been Recieved";
            BAL.updateParticipants(regID, status, amount, user, date);
            BAL.saveBudgetTracking(type, account, amount, 0, total_balance, detail, date);
            Response.Redirect("~/show_members.aspx");
        }
    }

}