Using INamingContainer in Controls

You use the INamingContainer Interface if you want your Control to create a ID namespace within the Page’s Control hierarchy. Basically you are setting an ID which wraps all the child controls.

In this example I shall show the difference in the HTML markup produced with and without and INamingContainer Interface being used on a Custom Control.

Here is a Control without the INamingContainer Inferface


namespace INamingContainerTestApp
{
    public class ExampleControl : Control
    {
        protected override void OnInit(EventArgs e)
        {
            TextBox textBox = new TextBox();
            textBox.ID = "txtBox1";

            base.Controls.Add(textBox);

            base.OnInit(e);
        }
    }
}

Now lets add the Control to a Web Page, by registering the Control


<%@ Register TagPrefix="Ctrl" Assembly="INamingContainerTestApp" Namespace="INamingContainerTestApp" %>

And placing the control on the page


This is the HTML that is rendered


As you can see the ID of the Control that is dynamically created inside my ExampleControl is called txtBox1

Now lets add the INamingContainer Interface to the ExampleControl


namespace INamingContainerTestApp
{
    public class ExampleControl : Control, INamingContainer
    {
        protected override void OnInit(EventArgs e)
        {
            TextBox textBox = new TextBox();
            textBox.ID = "txtBox1";

            base.Controls.Add(textBox);

            base.OnInit(e);
        }
    }
}

This is the HTML that is rendered


As you can see the ID now includes the ID of the parent Control



Comments

  1. deepak October 9th

    Comment Arrow

    No doubt!!! its an great explanation of INamingContainer Inferface.


Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.