tags:

views:

38

answers:

2

hi,

I have a basic IDE for a user control i am building. It allows me to add labels to a panel and move them around, like a very basic form designer.

When I add the controls to the panel at runtime, I'd like to give the control a unique name string like how the VS IDE tracks the controls it already has and adds an extra number when it creates the default control name. I have tried checking the controls collection each time a new control is added, but wasnt sure if there was a good string comparison method to return a name with a unique number on the end that hasn't been used yet.

A: 

The easiest way is to maintain the list of names in a sorted array, so you can choose the last one and create a new name based on it.

rep_movsd
A: 

You could create a quick and dirty ASP.NET page, dump a bunch of controls on it, run it and study the auto generated ClientIDs. The way ASP.NET (at least < v4) does it is to namespace the name and then add a number on the end. The namespace incorporates parts of the names/namespaces of the parent (container) controls.

So in your case, if a newly placed Button was dropped in to a div which was already in a div which was hosted on a page, the auto generated name would be:

div1_div1_button[x]

the [x] would be your generated number. An easy way to generate this is to get the count of child controls already in the parent container and increment it by 1. There is no reference to the hosting page because the namespacing is relative to the page. ASP.NET re-evaluates the auto generated names of server controls just before they are rendered, so that it is impossible to get a collision of names within the same page (if 2 identical control structures are housed within the same parent, then one of those controls will get 1 appended to its auto generated name, the other will get 2 appended, so no collision).

hope this helps :)

slugster
thanks guys, i used the sorted array method in the end, works perfectly.
The Code Shrew