2

I'm adding a label to a page using the code below, how would I set the position of the label (i.e top right)?

Label lbl = new Label();
lbl.Text = "Test";
lbl.ForeColor = System.Drawing.Color.Black;
lbl.Font.Size = 10;
lbl.Font.Bold = false;
lbl.Font.Name = "Arial";
Page.Controls.Add(lbl);

Thanks

Update: I really need to avoid using anything that can be altered via editing a file running on the server which is why I'm trying to do this at runtime.

Jamie
  • 2,465
  • 10
  • 28
  • 31
  • If you don't want people to edit your ASPX files then consider using a Web Application Project solution with the 'non-updatable UI' option. See http://www.asp.net/learn/hosting/tutorial-15-cs.aspx – Dan Diplo Apr 15 '10 at 14:47

2 Answers2

3

Add a PlaceHolder control to your page in the position you want to add the label to and then add the control as a child control of the PlaceHolder eg.

<asp:PlaceHolder ID="LabelPlaceHolder" runat="server">
</asp>

And then...

LabelPlaceHolder.Controls.Add(lbl);

Generally, though, dynamically adding controls at run-time is something you want to avoid. As is setting styling through in-line properties (use CSS instead). If you only want the Label to appear under specific circumstances then add it to the page with it's Visible property set to False and then set it to true to when you want to see it.

Dan Diplo
  • 25,076
  • 4
  • 67
  • 89
  • Thanks for that, please see my update above, basically I want to avoid adding anything in the aspx page. – Jamie Apr 15 '10 at 14:42
2

I'd suggest you do all formatting etc. with CSS - so, at runtime all you would specify is a css class for the control and let the browser do the rest.

Daren Thomas
  • 67,947
  • 40
  • 154
  • 200
  • 1
    I'd agree with that. Putting all the styling in a css file makes the site way easier to maintain. I always find it annoying when people set styles from the code-behind. – Kenneth J Apr 15 '10 at 14:15