Specifying a unique name for the control when added at runtime (like VS IDE)
I have a basic IDE for a custom control I am creating. This allows me to add labels to the panel and move them around like a very simple form builder.
When I add controls to a panel at runtime, I would like to give the control a unique name string, such as how the VS IDE keeps track of the controls that are already there and adds an extra number when creating the default control name. I tried to check the collection of controls every time a new control was added, but wasn't sure if there was a good string comparison method to return a name with a unique number at the end that hadn't been used yet.
a source to share
You can create a quick and dirty ASP.NET page, unload a bunch of controls, run it, and examine the automatically generated ClientIDs. The ASP.NET way (<v4 at least) is to number the name and then add the number to the end. The namespace includes parts of the name / namespaces of the parent (container) controls.
So in your case, if the new button was dropped into a div that was already in a div that was posted on the page, the auto-generated name would be:
div1_div1_button[x]
[x]
will be your generated number. An easy way to generate this is to get the counter of the child controls already in the parent container and increment it by 1. There is no link to the hosting page because the namespace is for that page. ASP.NET reevaluates the autogenerated names of the server controls just before rendering them so that it is impossible to get a name collision on the same page (if two identical control structures are placed inside the same parent, then one of these controls will get 1
appended to its autogenerated name and the other will add 2
, so there will be no collision).
hope this helps :)
a source to share