user1199346
user1199346

Reputation:

Using a custom control more than once on the same page / form .net

I have been building a custom control for some time now and overcome a number of hurdles. One challenge I have yet to resolve is the ability to use a custom control more than once on the same page.

I have a custom control that functions well on its own, but when two of the same controls are placed on the page the second control is able to control the first one. My guess is that the first one (control) is the first object and the second one is the same object. How can I make sure in the code that if I use the same control more than once on a page it will behave as two separate controls. Are there any specific things I should look at to make sure it allows it to be on a page more than once.

Thanks in advance.

Upvotes: 0

Views: 1777

Answers (2)

Ivan Karajas
Ivan Karajas

Reputation: 1101

Place a couple of instances of your custom control onto an ASPX page then view the HTML source and have a look at all the element IDs generated on each of the control instances. ASP.NET will automatically mangle the IDs of your control's children, prefixing them with the ID of the parent control. If you're outputting raw HTML, this might not happen. If there are any duplicate IDs, then that may be the cause of your problem, particularly if you're using client-side logic to manipulate the controls on the page.

Also, make sure that you're not using any session or application variables in your controls.

Upvotes: 1

goric
goric

Reputation: 11855

When you add multiple instances of a control, be sure to give them different IDs. Then when writing any code that will interact with them, reference them by that ID.

<%@ Register Src="controls/myControl.ascx" TagName="myControl" TagPrefix="uc1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainPlaceHolder" runat="server">
    <uc1:myControl ID="ctlFirst" runat="server">
    <uc1:myControl ID="ctlSecond" runat="server">
</asp:Content>

Then in the code behind:

ctlFirst.SomeProperty = true;
ctlSecond.SomeProperty = false;

Upvotes: 1

Related Questions