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");
        }
    }
}

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>