如何将复选框列添加到母版页中的网格视图? (或者,如何将Literal Control转换为Checkbox)

时间:2009-01-21 00:22:37

标签: c# asp.net gridview

我有一个gridview,我已经使用templatefield添加了一个复选框列(我希望用户能够选中/取消选中该框。我希望能够填充复选框,但是当我尝试转换列时作为RowDataBound事件的Checkbox,它出错了。由于Masterpage(我认为),我也无法进行FindControl

任何帮助将不胜感激!

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];

这是aspx代码:

<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>

1 个答案:

答案 0 :(得分:2)

控件[0]不是复选框。 ASP.NET会将一些HTML内容作为LiteralControl粘贴在那里,你需要查看哪个索引是你的复选框或坚持使用FindControl。

如果您只是尝试将true / false绑定到复选框,则可以在模板列中执行此操作:

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

IsChecked是绑定对象的属性。