【发布时间】:2010-08-06 20:53:17
【问题描述】:
我看到另一个线程有点像我的问题:
ASP.NET GridView Column - formatting telephone number
但我不知道它是否回答了我的问题,因为他正在使用代码隐藏来制作列。我所做的只是在 Visual Studio 中插入 GridView 控件。顺便说一句,数据正在填充到网格中,我现在只是想获取格式设置。
我正在使用 Microsoft Visual Studio Professional 2010。(我的数据库也使用 SQL Management Studio,但可能不需要此信息,只是尝试提供足够的信息以确保我正在做的事情被理解)
我正在用 ASP.NET 制作一个网站,后面有 Visual Basic.net 代码。
该网站基本上是一个联系人列表网站。
3 个文本框字段。名字、姓氏、主要电话号码。
添加记录按钮(从文本框中获取信息并插入数据库)
显示正在填充信息的数据库的 GridView
我有一个“主要电话号码”列,这会拉出一个电话号码以显示在 GridView 中。号码只有10位数字,没有格式……(即999-999-9999)
我正在尝试让 GridView 获取 9999999999 并使其 (999) 999-9999
如果我查看 DataFormatString,我尝试了许多“{0:(###) ###-####}”的组合,带和不带引号以及全零而不是井号。
通过我的研究,如果我想使用 DataFormatString,我需要将我的电话号码在我的数据库中设置为 int。所以我删除了我的表并将其从 varchar 重新创建为 int。我通过单击 Gridview 任务(GridView 右上角的箭头)...然后“编辑列”...然后在“选定字段”下单击列的名称...“主要电话号码”来访问 DataFormatString然后在“CommandField 属性”下向下滚动到“DataFormatString”。
我希望我没有说得太详细。我非常感谢所有的帮助。
我发现了这个:
http://www.tek-tips.com/viewthread.cfm?qid=328173
但我不知道我将如何使用它.. 看看如何,因为我的代码是由 Visual Studio 完成的......其中一些看起来像这样
更新:我最初发布了错误的代码,无论哪种方式,基于我所说的 Kelsey 能够为我提出一个可行的答案。
以下是我的新代码,其中包含凯利给出的更正。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="EmpId" DataSourceID="SqlDataSource1"
EmptyDataText="There are no data records to display." CellPadding="4"
ForeColor="#333333" GridLines="None" Height="136px" Width="299px"
AllowSorting="True">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="EmpId" HeaderText="EmpId" ReadOnly="True"
SortExpression="EmpId" Visible="False" />
<asp:BoundField DataField="FirstName" HeaderText="First Name"
SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name"
SortExpression="LastName" />
<%-- <asp:BoundField DataField="MainPhoneNumber" HeaderText="Main Phone Number"
SortExpression="MainPhoneNumber" />--%>
<asp:TemplateField HeaderText="Main Phone Number">
<ItemTemplate>
<asp:Literal ID="litPhone" runat="server" Text='<%# string.Format("{0:(###) ###-####}", Int64.Parse(Eval("MainPhoneNumber").ToString())) %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
【问题讨论】:
-
@patco258 你的
GridView代码在这里会很有帮助。 -
我用 GridView 代码更新了这篇文章,并提供了您提供的更正。有用。此外,在更改之前,不是模板字段而是边界字段,就像 Kelsey 在她的回答中所说的那样。
标签: asp.net data-binding gridview formatting string-formatting