zxc zxc - 1 year ago 102
ASP.NET (C#) Question

Gridview get Checkbox.Checked value

I have a gridview that has 10 columns populated by checkboxes. But instead of using

is there a way to get the checkbox.checked value by using a loop?

Current Code:

if (e.CommandName == "updaterow")
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = GridView1.Rows[index];
// TableCell BranchCode = selectedRow.Cells[0];
CheckBox cb101 = (CheckBox)selectedRow.FindControl("cb101");
CheckBox cb102 = (CheckBox)selectedRow.FindControl("cb102");
//...and so on


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<asp:TemplateField HeaderText="101">
<asp:CheckBox runat="server" id="cb101" AutoPostBack="false" Checked='<%# Eval("101").ToString()=="1" ? true : false %>' Enabled='<%#(String.IsNullOrEmpty(Eval("101").ToString()) ? false: true) %>'/>
....and so on
<asp:ButtonField ButtonType="Button" CommandName="updaterow" Text="Update"/>

Answer Source

try this,

using For Loop

foreach (GridViewRow row in GridView1.Rows)
     CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
     if (chk != null && chk.Checked)
       // ...

use in onrowcommand event and get cheked checkbox value.

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download