Any Way to Limit Instances of a Web User Control Element?

  • Thread starter Thread starter Jonathan Wood
  • Start date Start date
J

Jonathan Wood

I'm creating a Web User Control. It needs to include a few component
controls. But one of those component controls, a HiddenField control, should
only appear once on the entire page (at least with that name).

I'm not sure this is doable, but does anyone know if there's any way to
limit the number of instances on a page of a component of a Web User Control
to one, even if there are multiple instances of the Web User Control?

Thanks for any thoughts.

Jonathan
 
Can't you just implement INamingContainer on the user control and then the
hidden field will always have a unique name?
 
Howdy Jonathan!

Pop this logic somewhere in your user control.

If (Not
Me.Page.ClientScript.IsStartupScriptRegistered("HiddenFieldIsRegistered"))
Then
Dim hdn_Main As New HiddenField
With hdn_Main
.ID = "hdn_Main"
End With
Me.Page.Form.Controls.Add(hdn_Main)
Me.Page.ClientScript.RegisterStartupScript(Me.GetType(),
"HiddenFieldIsRegistered", "Yes", True)
End If
 
I'm not familiar with INamingContainer but I need exactly one instance of
the HiddenField with a pre-determined name.

Thanks.

Jonathan
 
<g>

You know, I kept thinking last night that what I needed was something like
ClientScript except for HTML instead of javascript!

I just put this together and it appears to be working perfectly.

I did get an error that "Yes" was undefined so I changed it to
Page.ClientScript.RegisterStartupScript(typeof(Page),
"HiddenFieldIsRegistered", "", false); and that seems okay.

Also, I like working with ClientScript because I plan to use it here for
other stuff in my control as well. (I'm thinking of writing client script to
copy the control-specific value to the one-and-only hidden field when my
control is clicked.)

Thanks again!

Jonathan
 
one thing to be wary of when using the typeof(page) when using the script
registration is that it won't work when inside of an updating update panel
except on the initial page load.

After that, there is no page object to attach it to, so it bombs. In those
cases, attach it to a control which is included in the update and all will be
well and good.

William
 
Okay, perhaps I'll change it to this.GetType(). I thought I read somewhere
that there were issues doing anything but Page in most cases. Unfortunately,
I don't recall why. There seemed to be some confusion regarding this.

Thanks.
 
Back
Top