Reputation:
I am using checkbox in gridview .... I am using it in 1st cell.... When I select the checkbox at run time, I need to get those values... but on selecting or on click to checkbox, it's not finding or value is taking as FALSE... how to write in asp.net backend and in c# code?
<asp:TemplateField>
<ItemTemplate >
<asp:checkbox id="ShowAddress" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Code-behind:
protected void Button1_Click(object sender, EventArgs e)
{
// Looping through all the rows in the GridView
foreach (GridViewRow di in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)di.FindControl("ShowAddress");
if (chkBx != null && chkBx.Checked)
{
/// put your code here
}
}
}
Is there any implementation to be done in script at page load?
Can anyone help?
Upvotes: 6
Views: 66068
Reputation: 3
Jakob Answer will work if below line is used. Even one control only in the cell, index need to be 1 not 0
CheckBox chk = row.Cells[0].Controls[1] as CheckBox;
Thank you Sam
Upvotes: -1
Reputation: 12908
int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = (CheckBox)GridView_AdminTags.Rows[i].Cells[0].FindControl("chkTag");
if (chk != null)
if (chk.Checked)
{
////.......;
}
i++;
}
i = 0;
Upvotes: 0
Reputation: 21
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Loadgridview();// its a correct
}// not Loadgridview() here if you load above error is occur
}
check it
Upvotes: 1
Reputation: 71
StringCollection idCollection = new StringCollection();
string strID = string.Empty;
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkDelete = (CheckBox) GridView1.Rows.Cells[0].FindControl("chkSelect");
if (chkDelete != null)
{
if (chkDelete.Checked)
{
strID = GridView1.Rows.Cells[1].Text;
idCollection.Add(strID);
}
}
}
for more details check this link: http://www.itworld2.com/ghowto.aspx?id=69
Upvotes: 4
Reputation: 14956
How do you populate your GridView? If you do this in Page_Load, make sure you are not doing it on postbacks (check IsPostBack).
Is your chkBx variable null?
The following code works:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
}
Upvotes: 4