Reputation: 6416
I have a simple input element with runat="server"
. This field is nested in a couple of layers of user controls and I am pulling the ID with a getter but the ID given is not the full generated ID.
//UserControl2.ascx nested inside of UserControl1.ascx
...
<input type="text" runat="server" id="newTextBox" />
...
//UserControl1.ascx.cs nested inside of Page1.aspx
...
public string NewTextBoxId;
protected void UserControl2PlaceHolder_Load(object sender, EventArgs e)
{
var c = LoadControl("~/Common/Controls/Shared/UserControl2.ascx");
NewTextBoxId = ((App.Common.Controls.Shared.UserControl2) c).newTextBox.ClientID;
}
The issue is that NewTextBoxId is set to "newTextBox" instead of the fully generated "ct100_ct100_MainContent_etc._newTextBox". The input's ID is rendered properly in the HTML but NewTextBoxId is not set properly. To make matters a bit more odd, the input's ID is rendered as "newTextBox" on my local instance but when I deploy to our staging server, it is rendered as "ct100_ct100..._newTextBox" in the HTML. Any ideas on this?
Upvotes: 0
Views: 324
Reputation: 2828
As noted in my comment. The LoadedControl c
has to be added to the ControlCollection of the current control prior to calling c.ClientID
. Adding to the ControlCollection will cause c
to be initialized.
//UserControl2.ascx nested inside of UserControl1.ascx
...
<input type="text" runat="server" id="newTextBox" />
...
//UserControl1.ascx.cs nested inside of Page1.aspx
...
public string NewTextBoxId;
protected void UserControl2PlaceHolder_Load(object sender, EventArgs e)
{
var c = LoadControl("~/Common/Controls/Shared/UserControl2.ascx");
this.Controls.Add(c);
NewTextBoxId = ((App.Common.Controls.Shared.UserControl2) c).newTextBox.ClientID;
}
Upvotes: 1