如何获取复选框
<asp:Table ID="mytbl" runat="server">
</asp:Table>
while (res.Read())
{
trow = new TableRow();
tcell1 = new TableCell();
tcell2 = new TableCell();
CheckBox ch = new CheckBox();
ch.CssClass = "chkBox";
ch.ID = res.GetInt32(1) + "_" + res.GetInt32(2);
//ch. = res.GetInt32(1) + "_" + res.GetInt32(2);
values.Add(res.GetInt32(1) + "_" + res.GetInt32(2));
tcell1.Controls.Add(ch);
tcell2.Text = res.GetString(0);
trow.Cells.Add(tcell1);
trow.Cells.Add(tcell2);
mytbl.Rows.Add(trow);
}
我想检查复选框已选中并将结果保存在数据库中
答案 0 :(得分:0)
据我所知,您希望在表中检查哪些复选框,然后根据您要对该已检查记录执行某些操作。
为此,您可以循环查看是否选中复选框。
HtmlTable table = (HtmlTable)Page.FindControl("mytbl");
foreach (HtmlTableRow row in table.Rows)
{
foreach (HtmlTableCell cell in row.Cells)
{
foreach (Control c in cell.Controls)
{
if (c is CheckBox && ((CheckBox)c).Checked)
{
//do some operation here
}
}
}
}
输出:
答案 1 :(得分:0)
看一下下面的例子。我没有访问你的数据库,所以我改变了我填充表格的方式,只是为了让它工作,但当你点击Save
按钮的逻辑循环遍历表格,让我们评估复选框(如果已选中或未选中):
代码背后:
protected void Page_Load(object sender, EventArgs e)
{
TableRow row1 = this.CreateRow("checkBox1", "chkBox", "Row 1");
TableRow row2 = this.CreateRow("checkBox2", "chkBox", "Row 2");
mytbl.Rows.Add(row1);
mytbl.Rows.Add(row2);
}
private TableRow CreateRow(string id, string css, string text)
{
var row = new TableRow();
var cell1 = new TableCell();
var cell2 = new TableCell { Text = text };
var checkBox = new CheckBox
{
CssClass = css,
ID = id
};
cell1.Controls.Add(checkBox);
row.Cells.Add(cell1);
row.Cells.Add(cell2);
return row;
}
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (TableRow row in mytbl.Rows)
{
CheckBox checkBox = row.Cells[0].Controls[0] as CheckBox;
string rowText = row.Cells[1].Text;
if(checkBox.Checked)
{
//Perform further processing
}
}
}
<强> .ASPX:强>
<form runat="server">
<asp:table id="mytbl" runat="server"></asp:table>
<asp:button id="btnSave" runat="server" text="Save" OnClick="btnSave_Click" />
</form>