How put label on a webform dynamically?

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.
 
M

Mark Fitzpatrick

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
 
J

Jeremy S.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top