我想在gridview中检查时更新数据。在我从复选框获取值之前,我的代码只返回数据库中的数据。我检查后想要当前值。
代码隐藏: -
protected void chkSelected_CheckedChanged(object sender, EventArgs e)
{
for (int rowIndex = 0; rowIndex < GridView1.Rows.Count; rowIndex++)
{
if (Convert.ToString(GridView1.Rows[rowIndex].Cells[4].Text) != "")
{
Response.Write("true");
}
else
{
Response.Write("fasle");
}
}
}
设计代码: -
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
CellPadding="4" GridLines="None" ForeColor="#333333" Font-Size="Smaller"
AutoGenerateColumns="False">
<RowStyle BackColor="#EFF3FB" />
<Columns>
<asp:BoundField DataField="LevelID" HeaderText="ลำดับข้อ" ReadOnly="True"
ItemStyle-Width="50" >
</asp:BoundField>
<asp:BoundField DataField="LevelDesc" HeaderText="คำถาม" ReadOnly="True"
ItemStyle-Width="250" >
</asp:BoundField>
<asp:BoundField DataField="ChoiceID" HeaderText="ข้อย่อย" ReadOnly="True"
ItemStyle-Width="50" >
</asp:BoundField>
<asp:BoundField DataField="ChoiceDesc" HeaderText="คำถามย่อย" ReadOnly="True"
ItemStyle-Width="400" >
</asp:BoundField>
<asp:TemplateField HeaderText="ใช่">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked='<%# Eval("Selected").ToString().Equals("True") %>'
AutoPostBack="true" OnCheckedChanged="chkSelected_CheckedChanged" CssClass="chkBox" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#507CD1" ForeColor="White" Font-Bold="True" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#0000CD" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
答案 0 :(得分:3)
使用GridViewRow
如下...您可以获取使用NamingContainer
属性检查的复选框的当前行,如下所示...
修改强>: - 更改标记并添加Hiddenfield以保持Selected的值,如下所示...
<asp:TemplateField HeaderText="ใช่">
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" Checked='<%# Eval("Selected").ToString().Equals("True") %>'
AutoPostBack="true" OnCheckedChanged="chkSelected_CheckedChanged" CssClass="chkBox" />
<asp:HiddenField ID="hiddenField1" Value='<%# Eval("Selected").ToString() %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
然后你可以得到Hiddenfield如下,它的值也是
protected void chkSelected_CheckedChanged(object sender, EventArgs e)
{
GridViewRow row = (GridViewRow)(((CheckBox)sender).NamingContainer);
HiddenField hdnCheck=(HiddenField)row.Cells[4].FindControl("hiddenField1");
if (Convert.ToString(hdnCheck.Value != "")
{
Response.Write("true");
}
else
{
Response.Write("false");
}
// Edit: You can easily get Checkbox which has been checked, and do your logic
CheckBox chkSelect=(CheckBox)sender;
if (chkSelect.Checked)
{
Response.Write("true");
}
else
{
Response.Write("false");
}
}