Reputation: 8923
I have a user control which has a textbox on it, now this usercontrol is on another user control which I am using on aspx page how can I get value of the textbox on the first user control.
Upvotes: 3
Views: 12968
Reputation: 6778
At the top of the .aspx page, add the below line above tag.
<%@ Register TagPrefix="Test" TagName="TestControl" Src="Test.ascx" %>
This directive registers the control so that it can be recognized when the page is processed. TagPrefix determines the unique namespace of the control, TagName is the name of the user control and Src is the path of the user control. Declare user controls like
<Test:TestControl id="TestControl" runat="Server"/>
Accessing and Setting User Controls Values in the .aspx Page: User can access and set the values of the User Control from .aspx page through properties,using javascript and in code-behind of aspx page.The details of it are shown below Using Properties If the test.ascx control has two textboxes and submit button.You can access the values of the textboxes in the control from an .aspx page by declaring public property in the .ascx page.
public string FirstName
{
get{return txtFirstName.Text;}
set{txtFirstName.Text = value;}
}
In .aspx page,you can access FirstName using
TestControl.FirstName
You can set the FirstName of the control from aspx page using
TestControl.FirstName = "Suzzanne"
Note:ref
Upvotes: 1
Reputation: 1571
I think it is easier to get the value off the Request. You could write a generic method like this to find it:
string get_value(string control_name)
{
var key = Request.Form.AllKeys.First(x => x.ends_with(control_name));
return Request.Form[key];
}
Upvotes: 0
Reputation: 95522
Write a property in your usercontrol to expose its contents, e.g.,
public string TextBoxValue
{
get { return txtControl1.Text; }
}
This way you can get the value of the textbox without exposing the whole textbox control as a public object.
Upvotes: 9
Reputation: 25775
Jon Limjap's answer provides the best solution for this kind of problem - Expose control values using Public properties.
However, if you do not want to do it this way (or you have to do this for a lot of controls and want to avoid creating Public properties for each control), you could use Reflection to "find the control" in the ChildControls of the required UserControl:
TextBox txt = UserControl1.FindControl("myTextBox") as TextBox;
if (txt != null)
{
string val = txt.Text;
}
Upvotes: 2