2012-11-13 51 views
1

我將用戶控件動態加載到頁面上。我通常是一個vb.net的人,通常可以通過,但這讓我難住。我試圖在加載之前將頁面中的變量傳遞給控件。將變量傳遞給控制頁面

繼承人就是我打電話的控制:

Control webUserControl = (Control)Page.LoadControl("~/controls/carousel-guards.ascx"); 

    phGuardsList.Controls.Add(webUserControl); 

我已經把下列財產上的旋轉木馬guards.ascx:

public String PostCode 
     { 
      get 
      { 
       return this.PostCode; 
      } 
      set 
      { 
       this.PostCode = value; 
      } 
     } 

但我似乎並沒有做有一個webUserControl.PostCode可用於我。

任何幫助將是非常讚賞

編輯 -當然,我必須引用控制。傻我!然而這不是讓我carousel_guards稱之爲:Error 96 The type or namespace name 'carousel_guards' could not be found (are you missing a using directive or an assembly reference?) C:\Development\Guards247\g247 Test\FindGuard.aspx.cs 197 13 g247 Test

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace g247_Test.controls 
{ 
    public partial class carousel_guards : System.Web.UI.UserControl 
    { 

     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 

     public String PostCode 
     { 
      get 
      { 
       return this.PostCode; 
      } 
      set 
      { 
       this.PostCode = value; 
      } 
     } 
    } 
} 
+0

從你如何寫屬性有一個問題,它是自引用。爲了避免這種情況,我通常使用'_'作爲前綴來編寫內部成員。 – AMember

回答

0

由於您正在將加載的控件投射到Control,因此無法從控件訪問該屬性。你應該把它轉換成你的控制類型。如果您的控件類名稱是CarouselGuards那麼您可以這樣做:

CarouselGuards webUserControl = (CarouselGuards)Page.LoadControl("~/controls/carousel-guards.ascx"); 

然後您可以訪問該屬性。

webUserControl.PostCode = "123"; 
+0

謝謝你 - 如果你能快速查看,我已經更新了我的問題,謝謝 – TMB87

+0

@TomBeech,你需要在代碼頂部指定'using g247_Test.controls;',或者右鍵點擊'carousel_guards '並選擇'解決' – Habib

+0

@TomBeech,不客氣 – Habib

1

您需要使用您的頁面的類名的工作。

var webUserControl = (carousel_guards)Page.LoadControl("~/controls/carousel-guards.ascx"); 

// now works 
webUserControl.PostCode = "17673"; 
phGuardsList.Controls.Add(webUserControl); 

如果沒有包括控制的參考,而不是發現類的名稱,你可以在ASPX插入行

<%@ Reference Control="~/controls/carousel-guards.ascx" %> 

或者只是拖放到頁面中,做出參考,然後刪除實際的控件,因爲它使其具有動態性。

0

使用鑄造你的控制型CarouselGuards代替Control

CarouselGuards webUserControl = (CarouselGuards)Page.LoadControl("~/controls/carousel-guards.ascx"); 
webUserControl.PostCode = "XXXX"; 

作爲一個側面說明,不要忘記爲對象的檢查空控制。