【问题标题】:Finding a user control from the main parent page从主父页面查找用户控件
【发布时间】:2014-08-05 16:13:08
【问题描述】:

您好,我有一个 aspx 页面 ResourceCategories.aspx,我在其中注册了两个用户控件:

我的问题是我必须访问用户控件 2)downloadPopUp in 1)ctlCategories on btn click 事件。

 protected void btnArrow_Click(object sender, EventArgs e) 

      {

            //lblMessages.Text = String.Empty;
            try
            {
          var userControl = FindControl("ctlPopUp") as UserControl;


            }
            catch (Exception ex)
           {
           }
      }

我仍然将 usercontrol 值设为 null。如何访问它?我只能访问我在第一个用户控件中注册的第二个用户控件,但不能从主 aspx 页面访问。即;在 ResourceCenter.ascx 中注册。我不想将用户控件嵌套在另一个用户控件中。有没有办法?

【问题讨论】:

  • 我认为你需要改写你的问题,你描述什么叫做什么是非常混乱的部分。此外,使用try/catch 捕获所有异常通常是不受欢迎的,尤其是当您的 catch 块为空时。
  • 我不确定我是否理解... aspx 和 c# 代码是否显示相同的页面?如果是这种情况,你不需要使用FindControl,你应该在后面的代码上有一个名为 ctlCategories 和 ctlPopUp 的属性
  • 否...代码在 ResourceCenter.ascx.cs 页面中。我尝试使用类访问 ctlpopup var userControl = ((ResourceCategories)this.Page).FindControl("ctlPopUp") as UserControl;我得到的值仍然是 null
  • var userControl=ctlPopUp 有效吗?正如我上面解释的那样,您需要更好地解释您的问题,以便清楚哪些代码与哪个文件一起使用。
  • OKie Mason... 我会试着解释一下。我必须尽快完成。 ASPX 主页面 ResourceCategories.aspx 有两个用户控件 ctlCategories(即 ResourceCenter.ascx usercontrol)和 ctlPopUp(DownLoadList.ascx usercontrol) 我需要的是 ResourceCenter.ascx 有一个按钮控件 btnArrow。点击 btnArrow_Click 我喜欢访问 ctlPopUp。希望它清楚

标签: c# asp.net


【解决方案1】:

使用此代码,您无需使用FindControl,因为您的页面上直接只有一个categoryPopup,使用runat="server" 声明:

<downloadPopUp:categoryPopup id="ctlPopUp" runat="server"></downloadPopUp:categoryPopup>

因此,在您的代码中,您可以直接使用ctlPopup 来访问控件。

【讨论】:

  • 确实如此。 ctlpopup 在主页(ResourceCategories.aspx.cs)中工作。问题是喜欢在 ResourceCategories.aspx.cs 和 ResourceCenter.ascx.cs 页面中访问 c​​tlpopup。如果我在 ResourceCategories.aspx 和 ResourceCenter.ascx(已在 ResourceCategories.aspx 中注册)页面中注册 ctlpopup,它就可以工作。不确定这是否是正确的做法。
  • 对于那个问题,在 ResourceCenter.ascx 中你需要使用Page.FindControl("ctlPopUp"),而不是FindControl("ctlPopUp")。不合格,FindControl 搜索当前控件,在您的示例中为 ResourceCenter.ascx,因此它没有找到弹出窗口,因为它位于不同的控件(页面)中。
猜你喜欢
  • 2015-04-30
  • 1970-01-01
  • 2011-06-29
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多