C# 2.0: Dynamically Adding Controls To A Web Page

Quick note: I have just learnt a more elegant way to dynamically add controls to a webpage and then access then via events etc. See code below. Note that most crucial part of this is the call to the FindControl (part of the page NamingContainer).

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Init(object sender, EventArgs e)
    {
        TextBox c = new TextBox();
        c.ID = "txtUserName";
        c.Text = "Arse, feck, drink";
        c.Visible = true;
        form1.Controls.Add(c);
    }
    protected void Page_PreRender(object sender, EventArgs e)
    {
        try
        {
            TextBox c = (TextBox)FindControl("txtUserName");
            Response.Write(c.Text);
        }
        catch
        {
            Response.Write("There was an error");
        }
    }
}

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.