Search code examples
c#asp.netweb-user-controls

How to find a control in a separate user control in the same page where it is registered


I have two user controls, in one of them I have a textbox, i need to retrieve its value from the second user control which is registered in the same page. How can i do this? I know the following line is wrong.. but i recall it was something like that.

TextBox myText = (TextBox)FindControl["mycontrol"] as TextBox;

Solution

  • If you need to access the value of the second control from the first control

    var textBox = this.Page.FindControl("SecondUserControl")
                      .FindControl("tbCardNumber") as TextBox;
    

    Where SecondUserControl is the id given in the page and tbCardNumber is the id given for the TextBox in the second control

    If you try to access the TextBox from a page

    var textBox = SecondUserControl1.FindControl("SecondUserControl")
                                    .FindControl("tbCardNumber") as TextBox;
    

    Where SecondUserControl1 is the ID of the control and you can access it in code behind.

    However, you can expose the the value of the text box via a property

    public string TextBoxValue
    {
       get
        {
            return tbCardNumber.Text;
        }
    }
    

    But you would still need FindControl method if you access it via another user control