2009-11-19 58 views

回答

0

我不完全確定你想要完成什麼,但它聽起來像想要從內容頁面訪問母版頁中包含的用戶控件的屬性。

您可以在您的母版頁中使用暴露用戶控件的文本屬性的公共屬性。

public string ShoppingCartText { 
    get { return ((TextBox)this.ShoppingCart.FindControl("TextBox1")).Text; } 
    set { ((TextBox)this.ShoppingCart.FindControl("TextBox1")).Text = value; } 
} 

然後從您的內容頁面,您可以設置文本框的值。您可以通過Page.Master屬性從內容頁面訪問母版頁的屬性。

Master.ShoppingCartText = "value" 
0

我所做的是通過後臺代碼中的公共函數訪問母版頁控件。因此,在後面的代碼母版頁

,我將宣佈類似:

public string getTextBoxValue() 
{ 
    return TextBox.Text; 
} 
+0

它不是主頁面控件。它在子頁面上,我想從母版頁上的og usercontrol後面的代碼訪問它。 – 2009-11-19 16:54:29

0

您可以通過控制樹遞歸找到一個網頁的任何控制。

這裏有幾個擴展方法,將這些代碼放入解決方案中的類文件中。

public static class ControlExtensions 
{ 
     public static IEnumerable<Control> FindAllControls(this Control control) 
     { 
      yield return control; 

      foreach (Control child in control.Controls) 
       foreach (Control all in child.FindAllControls())  
        yield return all; 
     } 

     public static Control FindControlRecursive(this Control control, string id) 
     { 
      var controls = from c in control.FindAllControls() 
          where c.ID == id 
          select c; 

      if (controls.Count() == 1) 
       return controls.First(); 

      return null; 
     } 
    } 

然後在你的用戶控件中使用這個。

TextBox whatYoureLookingFor = this.FindControlRecursive("theId") as TextBox; 

if(null != whatYoureLookingFor) 
    // whatever 
相關問題