[RESOLVED] Align label text in WebForms
I have programmatically created a label and would now like to align the text to the center. I am using C# with ASP.NET so cannot use the usual Windows.Form methods.
foreach (string grade in eNumGradesList)
{
lblENumGrade = new Label();
cellENumGrade = new TableCell();
// Position cells and specify details
lblENumGrade.Text = grade;
this.lblENumGrade.Text = this.lblENumGrade.Text.PadLeft(this.lblENumGrade.Text.Length + 25); // NOT WORKING
//lblENumGrade.Text.PadLeft(20); //NOT WORKING EITHER
cellENumGrade.Controls.Add(lblENumGrade);
cellENumGrade.BorderColor = System.Drawing.Color.Blue;
rowHeader.Controls.Add(cellENumGrade);
}
Re: Align label text in WebForms
Ok, so to center a label in a rectangle you just need to divide...
Code:
lblTest = new Label( );
// ... set width, height, other properties
Point location = new Point(
( this.width / 2 ) - ( lblTest / 2 ),
( this.height / 2 ) - ( lblTest.Height / 2 )
);
lblTest.Location = location;
this.Controls.Add( lblTest );
Re: Align label text in WebForms
Another option would be to use CSS. You can specify the CssClass property of the label to class you define in the stylesheet. In the definition of the style you can specify the 'text-align' property and set it to 'center'.
Re: Align label text in WebForms
Ahhh, I missed the "Webforms" part of the title ;).
Re: Align label text in WebForms
Yes I was thinking of specifying it in the stylesheet but I do not know how to specify the CssClass programmatically. I thought this could only be done in ASP.NET?
Re: Align label text in WebForms
You will still be using ASP.NET to specify the stylesheet programmatically. ASP.NET should be used in your case to render the page i.e. produce the markup elements with their attributes. Anything related to positioning should ideally be done through CSS. If you have an ASP.NET control you should be able to specify the CssClass. It is just another property like 'Text', etc. If that doesn't work you should be able to specify the 'class' through the attributes collection.
Code:
// Something like this...
lblTest.Attributes.Add("class", "centerAligned");
// Or this...
lblTest.CssClass = "centerAligned";
Re: Align label text in WebForms
Thank you, I will try that.