2010-05-24 57 views
0

我有一個類UserControlBase繼承System.Web.UI.UserControl和我的用戶控件繼承UserControlBase類。 UserControlBase具有用於所有用戶控件的一些常用功能。如何在父類中訪問標籤表單用戶控件?

我想將錯誤顯示功能放到UserControlBase中,以便我不必在所有用戶控件中聲明和管理它。用戶控件中的某些標籤中會顯示錯誤。問題是如何訪問UserControlBase中usercontrol中的標籤?我不想將標籤作爲參數傳遞。

回答

2

在你的用戶控件基地,僅露出標籤的文本值:

public abstract class UserControlBase : System.Web.UI.UserControl 
{ 
    private Label ErrorLabel { get; set; } 
    protected string ErrorMessage 
    { 
     get { return ErrorLabel.Text; } 
     set { ErrorLabel.Text = value; } 
    } 
    protected override void OnInit(EventArgs e) 
    { 
     base.OnInit(e); 
     ErrorLabel = new Label(); 
     Controls.Add(ErrorLabel); 
    } 
    //... Other functions 
} 

在繼承這個用戶控件:

public partial class WebUserControl1 : UserControlBase 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     try 
     { 

     } 
     catch (Exception) 
     { 
      ErrorMessage = "Error"; //Or whatever 

     } 

    } 

}