How To Align Text in an ASP.NET TextBox

(This applies to the .NET Framework v1.1. I'm not sure if things have changed in v2.0.

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


Mitthu said…
thnx .. first work around helped me.

Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

How To Mock Out Child Components In Unit Tests of Angular 2 Code