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

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
 
J

Joe Fawcett

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

William Niver

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
 
J

Jonathan Wood

I'm not familiar with INamingContainer but I need exactly one instance of
the HiddenField with a pre-determined name.

Thanks.

Jonathan
 
J

Jonathan Wood

<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
 
W

William Niver

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
 
J

Jonathan Wood

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top