Reputation: 2257
Is there a way to retrieve whether a Checkbox field is checked in a databound gridview in ASP.NET? I can retrieve all other cell values in a foreach
loop with cell.Text
. Since it is databound (to an ObjectDataSource) the columns and cells don't have explicitly set IDs and I can't seem to find a property that would let me know the cell contains a checkbox or just text. All cells are of type DataControlFieldCell so I can't check based on type either. Thoughts?
EDIT:
foreach (GridViewRow row in report_gv.Rows)
{
data += "<TR>";
foreach (TableCell cell in row.Cells)
{
data += "<TD>" + cell.Text + "</TD>";
//If this is a checkbox (bit value from the DB) cell.Text isn't going to return anything
}
data += "</TR>";
}
Upvotes: 1
Views: 2603
Reputation: 3951
foreach (GridViewRow row in myGridView) {
foreach (TableCell cell in row.Cells) {
foreach (Control ctrl in cell.Controls) {
if (ctrl is CheckBox) {
CheckBox cb = (CheckBox)ctrl;
// use cb
} else if (cell is TextBox) {
} else if (cell is Label) {
}
}
}
}
You can expand this to process however you need.
Upvotes: 1
Reputation: 14470
In GridView.RowDataBound Event you can access each and every checkbox
that inside each row.
Try something like this
<ItemTemplate>
<asp:CheckBoxList ID="chb1" runat="server">
</ItemTemplate>
protected void GvRowDataBound(object sender, GridViewRowEventArgs e)
{
var chb = (CheckBox) e.Row.FindControl("chb1");
var ischeck = false;
if(chb != null)
{
if(chb.Checked)
{
ischeck = true;
}
}
}
Upvotes: 0
Reputation: 3951
You can do it. But easier is to convert to a <TemplateField>
, which will allow you to assign an ID to your CheckBox
. Then your foreach goes:
foreach (GridViewRow row in myGridView) {
CheckBox myCB = (CheckBox)row.FindControl("gvIdentifier");
// Do something with myCB
}
Upvotes: 0
Reputation: 44605
you can use FindControl
on the GridViewItem
and search by the checkbox ID as you have it in the ItemTemplate
definition.
there are plenty of examples on FindControl GridView out there
for example check this out: checkBox in gridView
Upvotes: 0