How to add a control dynamically in C #?

6

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

    
asked by anonymous 17.04.2014 / 23:12

1 answer

6

Creating a control TextBox dynamically:

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, which appends to the page the component after the created ones manually. Example: If you have a Button on the screen and insert dynamically the TextBox will be created after the Button.

Can I insert the control in whatever position I want?

Yes, using the this.Page.Form.Controls.AddAt(Indice, Controle); method 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 to MasterPage is done differently:

ContentPlaceHolder MainContent = (ContentPlaceHolder)this.Master.FindControl("MainContent");
TextBox txtTeste = new TextBox();
txtTeste.ID = "txtTeste";
MainContent.Controls.Add(txtTeste);
  • The 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 Page_Load screen 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);
    }
    
17.04.2014 / 23:12