【问题标题】:Why is FindControl not working with my repeater?为什么 FindControl 不能与我的中继器一起使用?
【发布时间】:2009-12-11 22:34:54
【问题描述】:

我正在尝试更改在同一 LinkBut​​ton 的 onclick 事件期间嵌套在中继器的 ItemTemplate 部分内的一对服务器控件(特别是 LinkBut​​ton 和 Label)的可见性。我实际上已经找到了一个解决方案,但我不明白为什么它会起作用,而不是我之前尝试的方式。我最初尝试如下:

嵌套在中继器的 ItemTemplate 中

<asp:LinkButton ID="lnAdd" CommandArgument='<%#Eval("index") %>' runat="server" Text="Add" OnClick="lnAdd_Click"> </asp:LinkButton>

<asp:Label Visible="false" runat="server" ID="videoAdded" Text="Video Added"></asp:Label>

然后在那个 lnAdd_Click 函数里面我有:

Repeater1.FindControl("lnAdd").Visible = false;
Repeater1.FindControl("videoAdded").Visible = true;

其中Repeater1 是这些控件所在的中继器的ID。这似乎什么都不做(尽管它可以编译)。我认为这是因为某些未知原因未找到这些控件。

以下问题的最后一个答案是有效的:Server controls in an asp.net repeater

该解决方案似乎正在做一些与我尝试做的非常相似的事情。它甚至在中继器上使用 FindControl。唯一的区别(我可以看到)是它通过 sender 对象获取转发器。嗯,实际上,现在我考虑一下,当它实际运行时,元素的 id 被 .Net 更改为像ctl00_ContentPlaceHolder1_Repeater1_ctl02_lnAdd 这样的无意义的东西,所以也许这就是它没有找到它的原因。但同时,在工作解决方案中,我只给出“lnAdd”之类的普通 ID。 .Net 会自动翻译它吗?为什么它会为这个解决方案而不是我最初尝试的方式这样做?

无论如何,我觉得这里有一些基本的东西我还没有完全掌握,希望能得到一些启发:D

【问题讨论】:

    标签: c# asp.net repeater


    【解决方案1】:

    使用Repeater1.FindControl(..)... 的问题在于,您无法分辨出哪个特定的标签或链接按钮是针对的。它是一个转发器,因此每个此类项目都被分配一个唯一标识符作为 RepeaterItemCollection 的一部分。在标记中,您将其命名为“lnAdd”,但这不是它一旦生成的等等。

    作为参考,这是您在另一篇文章中所说的代码:

    protected void btnUpdate_OnClick(object sender, EventArgs e)
        {
            Button b = sender as Button;
            if (b != null)
            {
                RepeaterItem ri = b.Parent as RepeaterItem;
                if (ri != null)
                {
                    string name = null;
    
                    //Fetch data
                    TextBox txtName = ri.FindControl("txtName") as TextBox;
    

    我将解释上述工作的原因。首先,被点击的按钮是从发送者对象中转换而来的。我们知道它是一个按钮,因为它是更新按钮的点击处理程序。接下来,我们也知道按钮出现在中继器中,所以它的父级是RepeaterItem. 这就是ri 变量的初始化和转换方式。有了ri 可供我们使用,在其上使用 FindControl 现在将在 那个特定的 RepeaterItem 中找到给定的控件。

    【讨论】:

      【解决方案2】:

      您需要在包含被单击按钮的 RepeaterItem 上调用 FindControl,您在中继器的 OnItemCommand 处理程序中执行此操作,因此您将获得导致该命令的 RepeaterItem 实例。

      您必须在转发器标头中添加一个 OnItemCommand="ProcessCommands",然后添加一个 ProcessCommand 成员:

      protected void ProcessCommands(object source, RepeaterCommandEventArgs e)
      {
          LinkButton button = (LinkButton)e.Item.FindControl("lbAdd");
          button.Visible = false;
          ...
      }
      

      希望对你有帮助

      【讨论】:

      • 感谢您的回复,您的方法也有效,但我更感兴趣的是为什么我尝试过的方法失败了,而我提出的方法有效。不过,感谢您的回答!
      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 2011-12-25
      • 2020-10-08
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多