使用和不使用UpdatePanel控制Repeater中的范围

时间:2009-02-12 08:08:05

标签: asp.net updatepanel scope repeater

为什么下面的行给出了B行(Label2,UpdatePanel外部)的编译错误,但对于行A(Label1,UpdatePanel内部)没有?我原本期望两行都给出错误,因为两个控件都在同一个Repeater中,因此不应该在转发器之外直接访问,因为没有一个唯一的实例。

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

3 个答案:

答案 0 :(得分:1)

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

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

简短的回答是这是一个错误。你应该提交它,但它不应该是阻塞问题。

答案 1 :(得分:0)

真正的问题是为什么要在转发器中创建多个更新面板?把一个放在转发器外面并称之为好。或者,如果您只是想刷新一些文本而不使用更新面板,请使用一些客户端脚本回调来设置dom元素。看看这个http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/

答案 2 :(得分:0)

无论如何,这些都不合适。您不应该尝试直接引用ItemTemplate中包含的控件。

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

相关问题