views:

1159

answers:

1

Hi, I have a gridview that I have added a checkbox column using a templatefield (I want the user to be able to check/uncheck the box. I want to be able to populate the checkboxes, but when I try to cast the column as a Checkbox on the RowDataBound event, it errors. I also can't do a FindControl due to the Masterpage (I think)

Any help would be appreciated!

The RowDataBound:

if (e.Row.RowType == DataControlRowType.DataRow) {

  var RowData = (ResponderResultViewClass)e.Row.DataItem;

  // This control never gets found (due to the Masterpage I think)
  CheckBox chkBox = (CheckBox)e.Row.FindControl("chkCertified");

  // This throws an error saying "Can't convert LiteralControl to Checkbox
  CheckBox cb = (CheckBox)e.Row.Cells[4].Controls[0];

Here is the aspx code:

<asp:BoundField DataField="AnswerID" ControlStyle-Width="0" />
<asp:BoundField DataField="QuestionText" HeaderText="Question" />
<asp:BoundField DataField="AnswerText" HeaderText="Answer" ItemStyle-HorizontalAlign="Center" />
<asp:BoundField DataField="QualifyingGroupName" HeaderText="Qualifying Group" />
<asp:TemplateField HeaderText="Cert">
 <ItemStyle HorizontalAlign="Center" />
  <ItemTemplate>
   <asp:CheckBox ID="chkCertified" runat="server" />
 </ItemTemplate>
</asp:TemplateField>
+2  A: 

Controls[0] isn't the checkbox. ASP.NET will stick some HTML content in there as a LiteralControl, you'll need to look to see which index is your checkbox or stick with FindControl.

If you are just trying to bind the true/false to the checkbox, you can do so like this in your template column:

<asp:TemplateField HeaderText="Cert">
    <ItemStyle HorizontalAlign="Center" />
    <ItemTemplate>
        <asp:CheckBox ID="chkCertified" runat="server" Checked='<%# Eval("IsChecked") %>' />
    </ItemTemplate>
</asp:TemplateField>

Where IsChecked is a property on your bound object.

DavGarcia
Thanks David, control[1] did the trick!
Mark Kadlec
Added an alternate way to bind checkbox templates.
DavGarcia
Glad I could help, I've run into the same issue myself.
DavGarcia