Reputation: 833
I have a GridView and i am also using a checkbox in gridview that is like:
<asp:GridView ID="GridView2" CssClass="table table-striped table-hover" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SNo">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GFname" HeaderText="Name" />
<asp:BoundField DataField="Address1" HeaderText="Address 1" />
<asp:BoundField DataField="Address2" HeaderText="Address 2" />
<asp:BoundField DataField="MobileNo" HeaderText="Mobile No" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
cs
protected void btnsndwish_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView2.Rows)
{
CheckBox chk = (CheckBox)GridView2.FindControl("checkbox");
if (chk != null && chk.Checked)
{
string Query = "insert into SMSTable(MobileNo,MessageToSent,MessageDate,UserId,SentDate,Flag,GuestName) values ('" + g1.Cells[5].Text + "','" + txtmsg.Value + "','" + CurrentDate.ToString("dd-MMM-yyyy HH:mm:ss") + "','','" + CurrentDate.ToString("dd-MMM-yyyy HH:mm:ss") + "',0,'" + g1.Cells[2].Text + "')";
ds = obj.GetDataSet(Query);
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "Success", "alert('MSG ');", true);
}
}
but all the time I debug the program and it showed that the checked checkbox value is also null.
Upvotes: 2
Views: 3325
Reputation: 460108
It's not GridView2.FindControl("checkbox");
but g1.FindControl("checkbox");
:
foreach (GridViewRow row in GridView2.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("checkbox");
// ...
}
The NamingContainer
(that is where each Id must be unique) is the GridViewRow
not the whole GridView
. FindControl
doesn't search recursively.
Upvotes: 2