Custom control with multiple controls with the same ID problem?

advertisements

I have a very simple custom control ive defined below:

public class TestCtrl : WebControl
{
    protected override void OnInit(EventArgs e)
    {
        var btn = new Button() { ID = "test", Text = "text"};
        this.Controls.Add(btn);
    }
}

However, when I wish to place multiple instances of them on the same page, I get...

'Multiple controls with the same ID 'test' were found.

...when btn is clicked.

    protected void Page_Init(object sender, EventArgs e)
    {
        var ctrl1 = new TestCtrl() { ID = "ctrl1" };
        plc.Controls.Add(ctrl1);
        var ctrl2 = new TestCtrl() { ID = "ctrl2" };
        plc.Controls.Add(ctrl2);
    }

Is there a clean way to stop this from happening? Ive tried setting ClientIDMode to 'Auto' without any success, as the name property of the rendered markup is "test" on both buttons.

EDIT: Solved by adding 'INamingContainer' to the control public class TestCtrl : WebControl, INamingContainer{...}


EDIT: Solved by adding 'INamingContainer' to the control public class TestCtrl : WebControl, INamingContainer{...}