How to add a control to a ASP.NET
page dynamically using C # ?
How to add a control to a ASP.NET
page dynamically using C # ?
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.
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);
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);
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);
}