Control ID

M

MLibby

My custom control's ID is automatically generated at design time when
dragging the control onto the webform, however it is not generated when the
control is programmatically created in the code behind. Is there a way for a
control to automatically generate a unique id if one has not been assigned to
it?

For example...
private void Page_Load(object sender, System.EventArgs e)
{
MyControl control = new MyControl();
// the control.ID is not assigned. Is there a way for the control
// to automatically generate the ID if not assigned???
Form1.Controls.Add(control);
}
....

Mike



Mike
 
V

Viksi

Your control needs to implement the INamingContainer interface. The interface
has no requirements, it just tells .NET to assign an ID to it.
 
S

Steven Cheng[MSFT]

Hi Viksi,

Thanks for your reply. But I'm afraid the INamingContainer won't work for
this scenairo since it only ensure that all the sub controls in the
Control(which implemeent the INamingContainer) will have a unique ID under
that control's namespace. As for the control it self, it won't be assigned
a ID automatically if we create it programly.

Hi Mike,

If you do need to provide a auto assigned "Default ID" for your custom
controls, my suggestion is to assign the Control's ID property in its
Construntor. For example:

public MyControl()
{
this.ID = "ctrl" + DateTime.Now.Ticks;
}

And if we drag a control on form at design-time , the new assigned ID will
override it. How do you think? If you have any other ideas ,please also
feel free to post here. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 
N

news.microsoft.com

Try this:
private void Page_Load(object sender, System.EventArgs e)
{
MyControl control = new MyControl();
control.ID = "example";
Form1.Controls.Add(control);
}
 

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,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top