I have a GridView that has 10 columns populated by CheckBoxes. But instead of using FindControl()
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
}
ASPX CODE:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField HeaderText="101">
<ItemTemplate>
<asp:CheckBox runat="server" id="cb101" AutoPostBack="false" Checked='<%# Eval("101").ToString()=="1" ? true : false %>' Enabled='<%#(String.IsNullOrEmpty(Eval("101").ToString()) ? false: true) %>'/>
</ItemTemplate>
</asp:TemplateField>
....and so on
<asp:ButtonField ButtonType="Button" CommandName="updaterow" Text="Update"/>
</Columns>
</asp:GridView>
Try this,
Using foreach
Loop:
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Use it in OnRowCommand
event and get checked CheckBox value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
For run all lines of GridView don't use for
loop, use foreach
loop like:
foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
if (chkRow.Checked)
{
//if checked do something
}
}
}
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkbox = (CheckBox)row.FindControl("CheckBox1");
if (chkbox.Checked == true)
{
// Your Code
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With