Home All Groups Group Topic Archive Search About

GridView DataFormatString only works on Integers

Author
23 Feb 2006 9:54 PM
Bill H
Hello,

I'm trying to use the DataFormatString on a GridView Column to format a
char(10) phone field to  (xxx)xxx-xxxx

This works if the field is defined as an integer, but does not otherwise.
Is there another trick to using this Property ?

thanks
Bill

Author
24 Feb 2006 7:01 AM
Phillip Williams
Hi Bill,

You will have to use an ItemTemplate (with a label or TextBox) and then
either convert the field value to a number before applying the format string
or use a regular expression. 

For example in this line of code I remove any character that might prevent
the field from becoming a number, then convert it to a number then convert it
back again to a string using the format string that you already knew:

<asp:TextBox ID="lblPhone" runat="server" Text='<%#
                Convert.ToInt64(Eval("fldPhone").ToString().Replace(" ",
"").Replace(".", "").Replace("-", "").Replace("(", "").Replace(")",
"")).ToString("000-000-0000")
                 %>'></asp:TextBox>

In the following line I did the same string cleaning process but then used a
regular expression to achieve the same format:

<asp:Label ID="lblPhone" runat="server"
Text='<%#FormatPhone(Eval("fldPhone").ToString()) %>'></asp:Label>

The FormatPhone function is defined as this:

protected  string FormatPhone(string strPhone)
    {
        strPhone =  Convert.ToInt64( strPhone.Replace ("
","").Replace(".","").Replace("-","").Replace ("(","").Replace
(")","")).ToString ("0000000000");
        string ret= Regex.Replace(strPhone,
@"(?<AreaCode>\d{3})(?<seg1>\d{3})(?<seg2>\d{4})",
"(${AreaCode})-${seg1}-${seg2}");
        return ret;
    }

To understand the regular expression syntax you might review this demo on my
website in which I explained the use of named groups in regular expressions
http://www.webswapp.com/codesamples/aspnet20/regular_expressions/vb.aspx
Show quoteHide quote
"Bill H" wrote:

> Hello,
>
> I'm trying to use the DataFormatString on a GridView Column to format a
> char(10) phone field to  (xxx)xxx-xxxx
>
> This works if the field is defined as an integer, but does not otherwise.
> Is there another trick to using this Property ?
>
> thanks
> Bill
>
>
>