Dynamically Adding Web Controls

It is possible to dynamically add Web Controls to a Page by using the PreInit Page Event. In this example we will add a TextBox and LinkButton using the code behind and then also access the value in the TextBox from the LinkButton Click Event.

First let create the Page PreInit Event Handler method:


        protected void Page_PreInit(object sender, EventArgs e)
        {
              //your code here
        }

Now lets dynamically add the Web Controls


        protected void Page_PreInit(object sender, EventArgs e)
        {
            Trace.Write("Creating TextBox");

            TextBox textbox = new TextBox();
            textbox.ID = "myTextBox1";

            Trace.Write("Creating LinkButton");

            LinkButton linkButton = new LinkButton();
            linkButton.ID = "myLinkButton1";
            linkButton.Text = "Click me!";
            linkButton.Click += LinkButtonClick;

            Trace.Write("Adding Controls to Form");

            form1.Controls.Add(textbox);
            form1.Controls.Add(linkButton);
        }

Don’t forget to add them to the Control Collection inside the Form control.

Next lets add the LinkButton Event Handler method


        protected void LinkButtonClick(object sender, EventArgs e)
        {
            Trace.Write("Checking Control Collection");

            foreach (Control control in form1.Controls)
            {
                if (control.ID != "myTextBox1")
                    continue;

                Trace.Write("LinkButtonClick", string.Format("myTextBox1: {0}", ((TextBox) control).Text));
                break;
            }
        }

In this method we loop through the Controls within the Form to find the TextBox.

I also turned on Tracing within the Web.config, so that I could check it was all working correctly.



     


You can download the Dynamically Adding Web Controls project here



Comments

No comments yet.

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.