2012-04-23 64 views

回答

0

使用這樣的...

創建用戶控件一個公共財產,並使用您希望該值的用戶控件名調用屬性....

+0

我的賬戶被封鎖在這個網站上。現在我無法提出問題。 你能告訴我我該怎麼做才能提問? – Neeraj 2012-05-03 07:04:27

0

在MSDN上查看this article

簡而言之,如果您知道該ID,則可以訪問其他控件。

+0

我的賬戶被封鎖在這個網站上。現在我無法提問。你能告訴我我該怎麼提問? – Neeraj 2012-05-03 07:05:59

+0

請幫幫我。 – Neeraj 2012-05-03 07:11:13

1

你應該重構你的代碼,而不是依靠另一個UI控件上的某個標籤的內容。以與在該用戶控件中執行操作相同的方式獲取該值,或者在另一個類中提取該功能以避免代碼重複,並從兩個位置調用該值。

但是,如果您不想堅持使用這個現有的代碼,您應該創建接口並捕獲您不會從外部代碼調用的所有UserControls功能(在您的情況下:返回標籤文本)。然後在用戶控件中實現那個必須從外部調用的接口,之後是查找控件實例,可以通過枚舉所有Page子控件來實現。下面是按名稱在控制樹找到用戶控制界面簡單的示例代碼,它定義了控制必須返回一些標籤文字和類:

public interface IUserControl 
    { 
    string LabelText(); 
    } 

    public class PageUserControls 
    { 
    private Page parentPage; 

    public PageUserControls(Page myParentPage) 
    { 
     this.parentPage = myParentPage; 
    } 

    private IEnumerable<Control> EnumerateControlsRecursive(Control parent) 
    { 
     foreach (Control child in parent.Controls) 
     { 
     yield return child; 
     foreach (Control descendant in EnumerateControlsRecursive(child)) 
      yield return descendant; 
     } 
    } 

    public IUserControl GetControl(string controlName) 
    { 
     foreach (Control cnt in EnumerateControlsRecursive(this.parentPage)) 
     { 
     if (cnt is IUserControl && (cnt as UserControl).AppRelativeVirtualPath.Contains(controlName)) 
      return cnt as IUserControl; 
     } 
     return null;  
    } 
    } 

,那麼你必須實現在保持用戶控件界面該標籤:

public partial class WebUserControl1 : System.Web.UI.UserControl, IUserControl 
    { 
    public string LabelText() 
    { 
     return Label1.Text; 
    } 
    } 

最後用它從另一個用戶控制:

PageUserControls puc = new PageUserControls(this.Page); 
    string txt1 = puc.GetControl("WebUserControl1.ascx").LabelText(); 

BTW。方法EnumerateControlsRecursive是從SO回答到Finding all controls in an ASP.NET Panel?

+0

我的賬戶被封鎖在這個網站上。現在我無法提出問題。你能告訴我我該怎麼提問? – Neeraj 2012-05-03 07:05:24

相關問題