Reputation: 373
I have a gridview , in a column of the gridview i have 2 checkbox with different ids So i do a foreach loop after i click a button ( update button ) to loop the rows and check if the checkbox of that particular row is checked , then i want to update all rows together after clicking a button
I populate the gridview in Page_Load() , the foreach loop goes the correct number of loop according to the number of Rows but it won't go into my If statement on checking if the checkbox is checked
Here are my codes :
protected void btnUpdate_Click(object sender, EventArgs e)
{
int count = 0;
foreach (GridViewRow row in GridView1.Rows)
{
count++;
if (((CheckBox)row.FindControl("showBbtn")).Checked & ((CheckBox)row.FindControl("showCbtn")).Checked) // if 2 buttons are checked show error popout
{
Response.Write(@"<script language='javascript'>alert('You can only select Yes or No')</script>");
}
else
{
if (((CheckBox)row.FindControl("showCbtn")).Checked) // Won't enter
{
//Do something here.
}
if (((CheckBox)row.FindControl("showBbtn")).Checked) // Won't enter
{
// Do something here.
}
}
}
Response.Write(count);
}
And this is how i populate my gridview :
protected void Page_Load(object sender, EventArgs e)
{
BindQuestion(); // Foreach loop count is according to the number of rows
if (!Page.IsPostBack)
{
// BindQuestion(); // Can enter the if loop but the foreach loop count is only 1.
}
}
My aspx :
<asp:TemplateField HeaderText="Display">
<ItemTemplate>
<asp:CheckBox ID="showCbtn" runat="server" Text = "Yes" />
<br />
<asp:CheckBox ID="showBbtn" runat="server" Text = "No" />
</ItemTemplate>
</asp:TemplateField>
Upvotes: 1
Views: 8442
Reputation: 21
Try using this:-
CheckBox chbx = GridView1.HeaderRow.FindControl("CheckBox1") as CheckBox;
if (chbx != null && chbx.Checked)
{
Condition
}
Upvotes: 0
Reputation: 21
This method is also working
var checkBox = (CheckBox)item.FindControl("ckbActive");
Upvotes: 0
Reputation: 413
This may help you
foreach (GridViewRow gr in grdCreateDues.Rows)
{
CheckBox chkC = gr.FindControl("showCbtn") as CheckBox;
CheckBox chkB = gr.FindControl("showBbtn") as CheckBox;
GridViewRow Row = ((GridViewRow)chk.Parent.Parent);
if (chkC.Checked)
{
// update tblGridtable set xzy = @xyz
}
else if (chk.B.Checked)
{
// update tblGridtable set abc = @abc
}
}
Upvotes: 1
Reputation: 2788
There is problem in your If condition. You have given incorrect & sign, it should be two && sign.Replace
if (((CheckBox)row.FindControl("showBbtn")).Checked & ((CheckBox)row.FindControl("showCbtn")).Checked)
with
if (((CheckBox)row.FindControl("showBbtn")).Checked && ((CheckBox)row.FindControl("showCbtn")).Checked)
And also add the BindQuestion() inside ispostback.
Upvotes: 2