Reputation: 305
I have got the following user control:
<uc1:TextSearch runat="server" ID="tsClientName" HistoryQueryStringParameter="CN" LabelText="Client Name" />
I am trying to retrieve value of tsClientName field with the following code
TextBox txtbox = (TextBox)pnlAdvancedSearch.FindControl("tsClientName");
string var = txtbox.Text.ToString()
but I get this error:
Unable to cast object of type 'ASP.usercontrols_gridviewsearch_textsearch_ascx' to type 'System.Web.UI.WebControls.TextBox'
the user control field got the following code
<asp:TextBox runat="server" ID="txt" MaxLength="20" CssClass="title" />
Upvotes: 0
Views: 498
Reputation: 6916
So there is a TextboxText
property, and it has a get
accessor. That should be sufficient, as you're expecting to get the input from the user typing into the textbox.
Since the value of the TextboxText
property is blank, rather than containing the value of the textbox—which we can see it's being set to by the property—the problem must be in the code-behind of the usercontrol. It must be initializing the textbox at the wrong time.
Upvotes: 1
Reputation: 6916
There's no need to use FindControl
and casting for access such as this. In the code-behind of the usercontrol, add a property to retrieve the text:
public string NameText { get { return txt.Text; } }
Then, in the page that hosts the usercontrol, you can obtain the text using:
string nameText = tsClientName.NameText;
Upvotes: 1
Reputation: 174
You need to get the textbox control from user control as follows:
TextBox txtbox = (TextBox)pnlAdvancedSearch.FindControl("tsClientName").FindControl("txt");
Upvotes: 1