现在我查看了 ItemTemplates 上的 MSDN,但我没有看到如何通过 ID 访问它们。
这是一个链接http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.templatefield.itemtemplate.aspx
我认为这与访问代码隐藏或服务器脚本中的任何其他控件一样简单,但它不起作用。当我尝试通过 ID 引用它时,我不断收到“在当前上下文中不存在”错误。
我想要做的是访问标题复选框的选中属性并使用它来选择或取消选择 ItemTemplate 中的所有复选框。我还需要以后是否选择它们以用于我的代码中的其他用途。
这是我在项目中使用的 gridview 的代码。
<asp:GridView ID="ApplicationsGridView" runat="server"
   AutoGenerateColumns="True"
   visible="true"
   Font-Size="Smaller"
   CellPadding="5"
   Width="1200px"
   BorderStyle="Solid"
   BorderColor="Black"
   OnDataBinding="ApplicationsGridView_DataBinding">
<%-- Add the checkboxes declaratively  --%>
<Columns>
  <asp:TemplateField>
    <HeaderTemplate>
      <asp:CheckBox runat="server" ID="checkall" Checked="true" OnCheckedChanged="checkall_CheckedChanged" />
      <script runat="server">
        protected void checkall_CheckedChanged(object sender, EventArgs e)
        {
          if(checkall.checked)
          {
            foreach (GridViewRow row in ApplicationsGridView.Rows { }
          }         
        }
      </script>
    </HeaderTemplate>
    <ItemTemplate>
      <asp:CheckBox runat="server" ID="checkboxes" Checked="true" />
    </ItemTemplate>
  </asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#d2d2f2" />
<HeaderStyle Font-Bold="true" BackColor="#052a9f"  ForeColor="#eeeeff"  Font-Size="Medium"/>
</asp:GridView>
最初,我曾尝试在代码隐藏中访问 ID。但即使尝试使用服务器脚本,它仍然找不到它。如果不是通过 ID,我如何访问复选框?
编辑:这有效=)
    protected void checkall_CheckedChanged(object sender, EventArgs e)
    {
        //get whether its checked or not.
        CheckBox theCheckBox = sender as CheckBox;      
        //check them all if checked. Uncheck them all when unchecked.
        if (theCheckBox.Checked)
        {
            foreach (GridViewRow row in ApplicationsGridView.Rows)
            {
                CheckBox cb = row.FindControl("checkboxes") as CheckBox;
                cb.Checked = true;
            }
        }
        else if (!(theCheckBox.Checked))
        {
            foreach (GridViewRow row in ApplicationsGridView.Rows)
            {
                CheckBox cb = row.FindControl("checkboxes") as CheckBox;
                cb.Checked = false;
            }
        }
    }