开发者

how to access a label form user control in Parent class?

I have a class UserControlBase that inherits System.Web.UI.UserControl and my user controls inherit UserControlBase class. UserControlBase has some common functions that are used in all user controls.

I want to put error display function to UserControlBase as well so that I may not have to declare and manage it in all user controls. Error will be displayed in some label in usercontrol. Issue is how to access label which is in usercontrol in UserControlBase in function ? I do开发者_如何转开发n't want to pass label as argument.


In your UserControl Base, expose the text value of the label only:

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
}

In your user controls that inherit this:

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

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

        }

    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜