<%# 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>
Related Posts
Tags: asp.net, c sharp, format string, zip code






















[...] Maletsky presents Format String with String.Format and C# posted at Website Builders Resource. Jason Maletsky presents MySQL File Access, Access Denied [...]
Thanks! I did not know you had to convert it in C#…
This is interesting to learn. I only new few about this C#. I will try to do this. Thanks for sharing!