How To Align Text in an ASP.NET TextBox
I recently needed to right-align the text in an ASP.NET TextBox control, but the control lacks any sort of text-alignment property. There are, however, two workarounds I found for this issue.
The first is to simply add a style attribute to the control. This can be done as illustrated in the example code below, where txtKeyCode represents an ASP.NET TextBox (this is server-side code):
txtKeyCode.Attributes.Add( "Style", "text-align: right;" );
The second workaround is more involved but offers more flexibility. It entails using a stylesheet and creating a style class, then assigning this class to the control. With this method, not only can you align the text, but you can also specify all sorts of other properties as you usually do in a stylesheet. This is demonstrated below:
(In the stylesheet)
.RightAlignedTextBox
{
font-size: 12pt;
font-family: Arial;
text-align: right;
}
(Referencing the style class in the control tag)
<asp:TextBox id="txtKeyCode" runat="server" MaxLength="5" Width="100px" CssClass="RightAlignedTextBox" />
(Notice there's no period before the style class name.)
Both methods do the trick (and there are probably others), though I prefer the second due to additional flexibility.
Comments
Post a Comment