haansi
haansi

Reputation: 5730

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 don't want to pass label as argument.

Upvotes: 0

Views: 1190

Answers (1)

Daniel Dyson
Daniel Dyson

Reputation: 13230

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

        }

    }

}

Upvotes: 2

Related Questions