Chitika

Monday, October 15, 2012

Access usercontrol's values from page

 I've created user control named test.ascx with one textbox. Now I added this user control in my default.aspx page. How can i access that textbox value from my default.aspx page?
We can achieve this in two ways one is using FindControl() like

Method 1:
TextBox myTextBox = userControl.FindControl("YourTextBox") as TextBox;
string text = myTextBox.text;
The above way of finding the value of a control is not recommended and it is not 

good practice.



Method 2:


Use properties , 
public string Name
{
    get { return txtBox1.Text; }
    set { txtBox1.Text = value; }
}
Then from your default.aspx you can access it as 
String text = userControl.Name;
This is one best way of accessing a user control form page in asp.net.
You can also update the user control control values from page as,
userControl.Name= "something";
The values of the text box control can be written back to the user control by using the above statement . 
If we don't want to give access to out side the user control to change the text box value then we need to set the setter with access specifier as private.

No comments:

Post a Comment