2009-02-12 56 views
2

为什么以下给出的是行B(Label2,UpdatePanel外部)的编译错误,但不是A行(Label1,UpdatePanel内部)的编译错误?由于没有一个唯一的实例,因此我希望两条线路都会出现错误,因为两个控制器都位于同一个Repeater内,因此不应直接在Repeater外部访问。Repeater中的控制范围,包含和不包含UpdatePanel

<script runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     Label1.Text = Label1.ClientID; // Line A - compiles fine 
     Label2.Text = Label2.ClientID; // Line B - "The name 'Label2' does not exist in the current context" 
    } 
</script> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title>Untitled Page</title> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <div> 
      <asp:ScriptManager ID="ScriptManager1" runat="server" /> 
      <asp:Repeater runat="server" ID="Repeater1"> 
       <ItemTemplate> 
        <asp:UpdatePanel runat="server" ID="UpdatePanel1"> 
         <ContentTemplate> 
          <asp:Label ID="Label1" runat="server" Text="Label1" /> 
         </ContentTemplate> 
        </asp:UpdatePanel> 
        <asp:Label ID="Label2" runat="server" Text="Label2" /> 
       </ItemTemplate> 
      </asp:Repeater> 
     </div> 
    </form> 
</body> 
</html> 

回答

1

我敢打赌,如果你注释掉B行,你会在执行时遇到运行时错误。 Label1将成为空引用。

当您在ASPX页面中创建控件时,Visual Studio会尝试通过将控件添加到扩展页面类的设计器文件中的代码来帮助您。在这种情况下,它不应该添加一个。

简而言之,这是一个错误。你应该提交它,但它不应该是一个阻塞问题。

+0

不,也没有运行时异常。我向Page_Load添加了代码,将中继器绑定到包含两个项目的列表,其后是A行。结果是第二个中继器项目中的Label2文本被修改了。 – 2009-02-13 21:15:41

0

无论如何这些都是不正确的。您不应该试图直接引用ItemTemplate中包含的控件。

如果你想在运行时修改这些标签,你应该使用OnItemDataBound和FindControl。要在UpdatePanel中“查找”标签,您需要使用UpdatePanel.ContentTemplateContainer.FindControl()。

+0

谢谢你没有回答我的问题。正如我原来的问题清楚地表明的那样,“我会预料到两条线都会出错”,我想知道为什么事实并非如此。 – 2009-03-09 20:54:13