views:

996

answers:

2

I am adding a column to my gridview in code-behind as follows:

field = new BoundField();
field.HeaderText = "Phone Number";
field.DataField = "PhoneNumber";
field.HtmlEncode = false;
field.DataFormatString = "{0:###-###-####}";
gridView.Columns.Add(field);

However, the DataFormatString is not working because the PhoneNumber field is a string, not a numeric. Is there anyway to take care of that in the DataFormatString, or do I need to convert the data type before I get to this point?

+1  A: 

This is tricky. I'd probably format it 'manually' in the RowDataBound event of the grid.

I didn't show all of my code - the GridView is also instantiated and loaded from code-behind. Does it still have a RowDataBound event?
Mike C.
A: 

First choice is to do it in SQL

  select cast(phone as int) as Phone,...

If not, make that column a templated column and then you would have something like:

<asp:TextBox ID="TextBox1" runat="server" 
Text='<%#(DataBinder.Eval(Container.DataItem, "Phone")== System.DBNull.Value)?
"":
String.Format("{0:(###) ###-####}", 
Convert.ToInt64(DataBinder.Eval(Container.DataItem, "Phone"))))
%>'>
</asp:TextBox>
JBrooks
I'm adding the column in code-behind. Can I add a templated column in code-behind?
Mike C.
We are talking about addeding a templated column in the .aspx markup. See http://authors.aspalliance.com/aspxtreme/webforms/controls/addingtemplatefieldstogridview.aspx
JBrooks