我做了一个按钮,用于从数据库中删除文件,要删除文件,您需要选中一个复选框,然后单击一个按钮。为什么当我单击按钮并将复选框值写入html时,它总是显示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" />
后面的代码:
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)
}
}
}
}
我希望chk.Checked为True,因为我单击了它...
答案 0 :(得分:3)
如果要在Page_Load中绑定网格,请确保没有在if(!IsPostBack){}之外绑定网格。否则,您将失去每个回发中的复选框,从而失去复选框的状态。
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Bind Your Grid Here
}
}
答案 1 :(得分:1)
item.Cells [0] .Text将不起作用,因为网格列定义为TemplateField而不是BoundField。因此,我们需要使用FindControl访问该控件并从中检索文本。
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);
}
}
}