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

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

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4