Format String with String.Format and C#


<%# String.Format("{0:#####-####}", Convert.ToInt32(Eval("ZipCode"))) %>

It is necessary to convert the ZipCode field to an integer in this instance because the Format class expects an integer to properly format a number, otherwise it will only return the string or value that you passed to the Format class.

I am using this in conjunction with the MaskedEditExtender, which removes all formatting and will only save the characters entered into the form field onblur(). Here is the complete ASPX code used in the web form.


<asp:TextBox ID="ZipCode" runat="server"></asp:TextBox>

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
	ControlToValidate="ZipCode" Display="Dynamic"  SetFocusOnError="true"
	ErrorMessage="Zip Code Required"></asp:RequiredFieldValidator>

<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
	ControlToValidate="ZipCode" Display="Dynamic"
	ErrorMessage="Zip Code Invalid" SetFocusOnError="True"
	ValidationExpression="^\d{5}$|^\d{9}$"></asp:RegularExpressionValidator>

<cc1:MaskedEditExtender ID="MaskedEditExtender1"
	TargetControlID="ZipCode"
	Mask="99999-9999"
	MaskType="None"
	runat="server">
</cc1:MaskedEditExtender>


Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter

Related Posts

Tags: , , ,

Comments (3)

  1. [...] Maletsky presents Format String with String.Format and C# posted at Website Builders Resource. Jason Maletsky presents MySQL File Access, Access Denied [...]

  2. JM says:

    Thanks! I did not know you had to convert it in C#…

  3. This is interesting to learn. I only new few about this C#. I will try to do this. Thanks for sharing!

Leave a Reply





Donate

If you found this article useful and would like to see more like it this please consider making a donation.

Sponsors