Referencing subcontrols within UserControl

  • Thread starter Thread starter Mark Friedman
  • Start date Start date
M

Mark Friedman

Does anyone know how to reference a subcontrol of a UserControl within
client-side script. For example, if I have a TextBox as one of the elements
of my UserControl with an id of "MyTextBox", how do I reference it within
some jscript function. If I try to just reference it as MyTextBox I get an
error saying that MyTextBox is undefined.

From looking at the generated source, I believe that there are two issues
involved. One is that the subcontrol's ID is getting renamed to something
like Foo1_MyTextBox, where Foo is the name of the UserControl. The second
issue is that the reference seems to need to be qualified by it's parent
form's ID, e.g. Form1.Foo1_MyTextBox. If I reference the TextBox that way
it works, but there are a couple of problems, First, I can't be sure what
the renaming be. I assume that if I have more than one instance of the
UserControl on a form that the prefix will change. The second problem is
that I don't know what the ID if the containing form is going to be so I
can't know how to qualify the TextBox's name.

Thanks in advance.

-Mark
 
Use the ClientID property to get the name of the control in the resulting
HTML.
 
I take your response to refer to client-side script that would be generated
by my UserControl, but what I'd really like to do is just write the script
code directly in the page. Is there a way to do what I want without
generating the script in the control?

-Mark
 
<script>
var ctl = document.getElementById('<% =
FindControl("myusercontrol").FindControl("mysubcontrol").ClientId %>');
</script>
 
Back
Top