问题
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:
This is tricky. I'd probably format it 'manually' in the RowDataBound event of the grid.
回答2:
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>
来源:https://stackoverflow.com/questions/1180403/asp-net-gridview-column-formatting-telephone-number