Question : ASP.NET - How to change the text property of a label that is inside a user control?

Hi Experts,

I have an ascx (1) page that has another ascx (2) inside it. I wish to change the text property of a label that is inside the ascx 2.

- I defined a public variable inside ascx 2.
- I called the variable by calling the . from within ascx 1 and changed it's value inside the click event of a button.

This didn't work. But when I moved the code from the click event into the load event it worked. But I want to do it on the click event!

What do I do?

Answer : ASP.NET - How to change the text property of a label that is inside a user control?

That is because first all controls are loaded and then the button click is fired so you can do any of these:
1: Find the label in UC2 in your button click in UC1 and change the text like:

protected void Button1_Click(object sender, EventArgs e)
    {
        Label lbl = (Label)MyUC2.FindControl("Label1");
        if (lbl != null)
        {
            lbl.Text = "NewValue";
        }
}
Or
2: A Property in UC2 like below:

private string _myLabelText;
    public string MyLabelText
    {
        get
        {
            return _myLabelText;
        }
        set
        {
            _myLabelText = value;
            OnPropertyChanged(new PropertyChangedEventArgs("mylabeltext"));
        }
    }

    private void OnPropertyChanged(PropertyChangedEventArgs propertyChangedEventArgs)
    {
        Label1.Text = this.MyLabelText;
    }

and the button click will look like below:

protected void Button1_Click(object sender, EventArgs e)
    {
        MyUC2.MyLabelText = TextBox1.Text;
    }
Random Solutions  
 
programming4us programming4us