How to add a control dynamically in C#?

Asked

Viewed 2,229 times

6

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

  • It wouldn’t be ASP.NET instead of just ASP?

  • @Miguelangelo Corrected.

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 method is used this.Page.Form.Controls.Add(); attaching the component to the page after manually created. Example: If you have a Button on the screen and dynamically insert the Textbox will be created after the Button.

I can insert the controller in the position I want?

Yes, using the method 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 of Maincontent

To add a control to Masterpage is made in a different way:

ContentPlaceHolder MainContent = (ContentPlaceHolder)this.Master.FindControl("MainContent");
TextBox txtTeste = new TextBox();
txtTeste.ID = "txtTeste";
MainContent.Controls.Add(txtTeste);
  • The controls added dynamically 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;
    }
}

In the Page_load from the screen we add to 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);
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.