ASP.NET GridView Column - formatting telephone number

断了今生、忘了曾经 提交于 2019-12-24 08:14:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!