How put label on a webform dynamically?

  • Thread starter Thread starter Ronald S. Cook
  • Start date Start date
R

Ronald S. Cook

I would like to put a label (or any control) on a webform all from the code.
I.e. something like this:

protected void Page_Load(object sender, EventArgs e)
{
Label TestLabel = new Label();
TestLabel.Text = "Hello world";
}

without having to have anything like this already on the page:

<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

I.e. dynamically build a web page.

Thanks for any info.
 
Label Testlabel = new Label();
TestLabel.Text = "Hi there";
Page.Controls.Add(TestLabel);

Usually though, what you want to do is put a PlaceHolder control on the
page. That way you can dynamically add things like a Label into specific
regions.

Keep in mind, when you try to do this with LinkButtons things tend to blow
up in your face because the LinkButton has to be added early enough to catch
any events it fires. Dynamically created controls that have events linked to
them are tricky to master so be wary about them and do a good bit of reading
on dynamically added controls before trying to work with them.

Hope this helps,
Mark Fitzpatrick
Microsoft MVP - Expression
 
In addition to the PlaceHolder approach, you can also use ParseControl to
parse a control (or multiple Web server controls) from a string. Google
ParseControl and you'll come up with some examples. This makes it easy to
mix static HTML with Web Server controls and dynamically insert the whole
shootin' match into your page (or PlaceHolder.Controls collection) at
runtime.

- HTH
 
Back
Top