无法访问< %%>内的控件(代码标签)在转发器的ItemTemplate中

时间:2011-09-05 08:59:33

标签: asp.net

没有转发器这是有效的,但是在转发器中写这个只是编译错误

<asp:Repeater runat="server" ID="rep1">
    <ItemTemplate>
      <li>
          <o:TextBox runat="server" ID="txtLastName" />
<% 
//this doesn't works outside of the repeater but here it doesn't
txtName.Text = txtLastName.ClientID;
%>                               
          <o:TextBox runat="server" ID="txtName"  />
       </li>
     </ItemTemplate>
</asp:Repeater>

1 个答案:

答案 0 :(得分:3)

您只能在ItemTemplate <%# %>中使用DataBind语法。如果要引用其他控件,请使用NamingContainer

<asp:Repeater runat="server" ID="rep1">
    <ItemTemplate>
      <li>
          <o:TextBox runat="server" ID="txtLastName" />
          <%# Container.FindControl("txtLastName").ClientID %>    
          <o:TextBox runat="server" ID="txtName"  />
       </li>
     </ItemTemplate>
</asp:Repeater>

否则,您始终可以挂钩ItemDataBound来操纵服务器端的控件。

protected void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{       
   if (e.Item.ItemType == ListItemType.Item 
                || e.Item.ItemType == ListItemType.AlternatingItem)
   {
       var txtLastName = e.Item.FindControl("txtLastName") as TextBox;
       var txtName = e.Item.FindControl("txtName") as TextBox;

       ...
   }
}