Reputation: 35
I made a button to delete files from a database, to delete a file you need to check a checkbox and then click a button. somewhy when i click the button and write the checkbox value to the html it always says false...
ASPX:
<asp:GridView HorizontalAlign="Center" ID="GridView1" runat="server" class="" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" DataKeyNames="ID">
<Columns>
<asp:TemplateField HeaderText="Name">< ItemTemplate >
< asp:LinkButton ID = "LinkButton2" runat="server" OnClick="OpenDocument" Text='<%# Eval("File_Name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">< ItemTemplate >
< asp:CheckBox ID = "CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button runat="server" Text="Update" ID="Update" class="button" OnClick="UpdateTable" Style="font-size: 20px" />
Code Behind:
protected void UpdateTable(object sender, EventArgs e)
{
foreach (GridViewRow item in GridView1.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
if (chk != null)
{
//This is being written and always false
Response.Write(chk.Checked);
if (chk.Checked)
{
//Delete the item. (never being executed)
}
}
}
}
I expected chk.Checked to be True since i've clicked it...
Upvotes: 1
Views: 615
Reputation: 419
item.Cells[0].Text will not work as the grid column is defined as TemplateField and not as BoundField. So we need to access the control using FindControl and retrieve the text from it.
protected void UpdateTable(object sender, EventArgs e)
{
foreach (GridViewRow item in GridView1.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
if (chk != null)
{
//This is being written and always false
Response.Write(chk.Checked);
if (chk.Checked)
{
//Delete the item. (never being executed)
}
}
LinkButton lnk = (LinkButton)item.FindControl("LinkButton2");
if (lnk != null)
{
Response.Write(lnk.Text);
}
}
}
Upvotes: 1
Reputation: 1350
If you are binding your grid in Page_Load, Make sure you are not binding your grid outside of if(!IsPostBack){}. Otherwise you'll loose the checkboxes on each postback and so losing the status of checkboxes.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Bind Your Grid Here
}
}
Upvotes: 3