2009-02-23 54 views
2

我在我的項目,我加入到網頁編程在頁面的Page_Load事件處理程序,像這樣一個用戶控件(.ascx):以編程方式添加用戶控件不創建它的子控件

Controls.Add(new MyProject.Controls.ControlWidget()); 
Databind(); 

當我嘗試從控件本身訪問控件的子控件時,它們不存在。

public override void DataBind() 
{ 
    myrepeater.DataSource = GetDataSource(); 
    // throws an exception because myrepeater is null 

    base.DataBind(); 
} 

如何訪問用戶控件的子控件?我曾嘗試將EnsureChildControls()調用添加到我的DataBind()重寫中,但這似乎沒有什麼區別。

回答

5

您需要使用LoadControl加載它,而不僅僅是實例化類。 LoadControl在幕後實現「魔術」,將所有東西都捆綁起來並實例化前端。

+0

你說對了 - 謝謝! – kristian 2009-02-23 12:01:02

0

編輯:我missunderstood你的問題,

嘗試給你的用戶控件添加到您的網頁:

UserControl uc = new UserControl(); 
uc.LoadControl(Server.MapPath("MyUserControl.ascx"); 
this.Controls.Add(uc); 
+0

只需在頁面上使用LoadControl。 – James 2010-01-26 12:15:26

相關問題