1

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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?
0

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>

2 Comments

I'm adding the column in code-behind. Can I add a templated column in code-behind?
We are talking about addeding a templated column in the .aspx markup. See authors.aspalliance.com/aspxtreme/webforms/controls/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.