How to find a control in a separate user control in the same page where it is registered
-
28-05-2021 - |
题
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;
解决方案
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
其他提示
The code you have should work, except you have too many casts
TextBox myText = FindControl["mycontrol"] as TextBox;
MSDN documentation on FindControl which returns a Control
, which is the base class of the Textbox, so this cast should work as long as the control found is a textbox