Reputation: 11
how to get checkbox is checked when checkbox is in table rows
<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);
}
I want check checkbox is checked and save result in database
Upvotes: 1
Views: 3508
Reputation: 4588
What I understood that you want to see which checkboxes are checked in the table then based on that you want to do some operation on that checked records.
So to do that you can loop and see checkboxes are checked or not.
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
}
}
}
}
Output:
Upvotes: 0
Reputation: 17019
Have a look at the example below.I don't have access to your database so I changed the way I populate the table on my side just to get it working but when you click the Save
button the logic loops through the table and let's you evaluate the checkbox(if it was checked or not):
Code behind:
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>
Upvotes: 2