简体   繁体   English

如何从aspx页面访问用户控件ID?

[英]How to access usercontrol id from the aspx page?

I have a usercontrol as given below. 我有一个用户控件,如下所示。

public partial class lcont : System.Web.UI.UserControl
{
  public delegate void mydel(string str);

  protected void Page_Load(object sender, EventArgs e)
  {
  }
  public event mydel myevent;

  public void butt_click(object sender, EventArgs e)
  {

    if (myevent != null)
    {
        myevent(tv.SelectedNode.Value);
    }  
  }
}

And a test.aspx which has used the usercontrol of the above. 还有一个使用上面用户控件的test.aspx。

<body>
 <form id="form1" runat="server">
 <uc1:lcont ID="lcont1" runat="server" />
 <div>
 <asp:Label ID ='lbl' runat="server" Text ="lbl"  />
 </div>
 </form>
</body>

Its codebehind is: 其背后的代码是:

protected void Page_Load(object sender, EventArgs e)
{

   lcont1.myevent += delegate(string st)
    {
        lbl.Text = st;
    };

}

As you can see here i am able to call "lcont1" which is the id of usercontrol in the codebehind of aspx file. 如您在这里看到的,我能够调用“ lcont1”,这是aspx文件背后代码中usercontrol的ID。

Now the question is: I want to do the same thing but this time with the aspx file that hasn't directly implemented the usercontrol but has inherited the master page which has implemented the usercontrol. 现在的问题是:我想做同样的事情,但是这次使用的aspx文件没有直接实现usercontrol,但是继承了实现了usercontrol的母版页。

IN other word, the usercontrol is implemented in the master page and the master page is implemented by the aspx page.Now i want to access the usercontrol id in the aspx page just like the above example.Please Help! 换句话说,usercontrol是在母版页中实现的,而母版页是由aspx页实现的。现在我想像上面的示例一样在aspx页中访问usercontrol id。

The way I would do it is this... 我要做的就是这样

Create a public function/property in your MasterPage that exposes the UserControl 在您的MasterPage中创建一个公开功能/属性,以公开UserControl

public lcont GetLcont1()
{
   return lcont1;
}

Then in your .aspx you can cast the MasterPage 然后,在您的.aspx您可以投射MasterPage

MyMasterPage myMaster = (MyMasterPage)Page.Master;

Now you should be able to get your UserControl and do what you need with it 现在,您应该可以获取UserControl并使用它进行所需的操作

lcont lcont1 = myMaster.GetLcont1();
lcont1.doSomething();

Update 更新

As the OP requires spoon-feeding, here is the code-behind for the .aspx page... 由于OP需要用勺子喂食,因此这是.aspx页的代码隐藏...

protected void Page_Load(object sender, EventArgs e)
{
  // Note: replace "MyMasterPage" with the name of your master page class
  MyMasterPage myMaster = (MyMasterPage)Page.Master;
  lcont lcont1 = myMaster.GetLcont1();
  lcont1.myevent += delegate(string st)
  ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM