2013-04-03 26 views
1

我有一個Default.aspx頁面,我在其中使用了一個usercontrol。在usercontrol.cs中的某些條件中,我必須調用Default.aspx.cs頁面中存在的函數(即用戶控件的父頁面)。請幫助並告訴我如何完成這項任務。從用戶控件調用父頁面功能

+0

[這會幫助你](http://stackoverflow.com/questions/623136/calling-a-method-in-parent-page-from-user-control?rq=1) – Damith

回答

0

你必須在Page財產轉換爲實際類型:

var def = this.Page as _Default; 
if(def != null) 
{ 
    def.FunctionName(); 
} 

的方法必須是public:

public partial class _Default : System.Web.UI.Page 
{ 
    public void FunctionName() 
    { 

    } 
} 

但是請注意,這不是最好的做法,因爲你是硬將UserControlPage聯繫起來。通常UserControl的一個目的是可重用性。這裏不再有了。從UserControl與其頁面進行通信的最佳方式是使用可由頁面處理的自定義事件。

Mastering Page-UserControl Communication - event driven communication

-2

試試這個

MyAspxClassName aspxobj= new MyUserControlClassName(); 
    aspxobj.YourMethod(param); 
+1

你在開玩笑嗎?除了'UserControl'不是'Page''這個事實,如果你想訪問'Page或UserControl'上的控件,使用構造函數來創建一個頁面(或'UserControl')將不起作用,因爲這個實例不是通過頁面的生命週期從ASP.NET創建的。 –

0

事件添加到用戶控件:

public event EventHandler SpecialCondition; 

引發此事件,您的用戶控件中,當條件滿足:

private void RaiseSpecialCondition() 
{ 
    if (SpecialCondition != null) // If nobody subscribed to the event, it will be null. 
     SpecialCondition(this, EventArgs.Empty); 
} 

然後在包含用戶控制你的頁面,監聽的事件:

public partial class _Default : System.Web.UI.Page 
{ 
    public void Page_OnLoad(object sender, EventArgs e) 
    { 
     this.UserControl1.OnSpecialCondition += HandleSpecialCondition; 
    } 

    public void HandleSpecialCondition(object sender, EventArgs e) 
    { 
     // Your handler here. 
    } 
} 

您可以將EventArgs改變的東西,如果需要的是傳遞價值,更實用。

0

parent.aspx.cs

public void DisplayMsg(string message) 
{ 
    if (message == "" || message == null) message = "Default Message"; 
    Response.Write(message); 
} 

要調用父頁面的功能由用戶控制使用以下命令: UserControl.ascx.cs

this.Page.GetType().InvokeMember("DisplayMsg", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { "My Message" }); 

這正常工作對我..

相關問題