How to add a control dynamically in C#?

Question:

How to add a control to an ASP.NET page dynamically using C# ?

Answer:

Dynamically creating a TextBox control:

TextBox txtTeste = new TextBox();
txtTeste.ID = "txtTeste";
this.Page.Form.Controls.Add(txtTeste);

To insert this component on the screen, the this.Page.Form.Controls.Add(); method is used this.Page.Form.Controls.Add(); that attaches to the page the component after the ones created manually. Example: If you have a Button on the screen and dynamically insert the TextBox will be created after the Button.

Can I insert the control in the position I want?

Yes, using this.Page.Form.Controls.AddAt(Indice, Controle); using the previous example would look like this: this.Page.Form.Controls.AddAt(0, txtTeste);

Control in MasterPage is added outside MainContent

To add a control on MasterPage is done in a different way:

ContentPlaceHolder MainContent = (ContentPlaceHolder)this.Master.FindControl("MainContent");
TextBox txtTeste = new TextBox();
txtTeste.ID = "txtTeste";
MainContent.Controls.Add(txtTeste);
  • Dynamically added controls have all the properties of a manually added control.

Adding and styling a GridView dynamically:

/* Classe exemplo */
public class Aluno
{
    public string Nome { get; set; }
    public int? RA { get; set; }

    public Aluno(string nome, int? ra)
    {
        Nome = nome;
        RA = ra;
    }
}

On the screen's Page_Load we add the Grid and the data:

    protected void Page_Load(object sender, EventArgs e)
    {
        /* Lista criada para popular a Grid */
        List<Aluno> Alunos = new List<Aluno>();
        Alunos.Add(new Aluno("João", 2013));
        Alunos.Add(new Aluno("Maria", 2014));

        GridView gvAlunos = new GridView();
        gvAlunos.ID = "gvAlunos";
        gvAlunos.BorderColor = Color.White; /* Alterando cor da borda da Gridview */
        gvAlunos.HeaderStyle.BackColor = Color.RoyalBlue; /* Alterando a cor do background do Header */
        gvAlunos.HeaderStyle.ForeColor = Color.White; /* Alterando a cor da fonte do Header */
        gvAlunos.DataSource = Alunos;
        gvAlunos.DataBind();
        this.Page.Form.Controls.Add(gvAlunos);
    }
Scroll to Top