DataGrid控件实用小技巧 (4)

来源:岁月联盟 编辑:zhuzhu 时间:2005-11-22
让我们看一下如何通过使用BoundColumn标记来进一步增强前面的示例。正如前面所提到的,我们不想显示FAQID或FAQCategoryID列,并且我们希望对数字列(ViewCount)和日期/时间列(DateEntered)设定格式。另外,我们希望数字列的值居中。这些均可通过几行易于阅读易于理解的代码完成:







<asp:DataGrid runat="server" id="dgPopularFAQs" BackColor="#eeeeee" Width="85%"HorizontalAlign="Center"Font-Name="Verdana" CellPadding="4"Font-Size="10pt" AutoGenerateColumns="False"><HeaderStyle BackColor="Black" ForeColor="White" Font-Bold="True" HorizontalAlign="Center" /><AlternatingItemStyle BackColor="White" /><Columns><asp:BoundColumn DataField="CatName" HeaderText="Category Name" /><asp:BoundColumn DataField="Description" HeaderText="FAQ Description" /><asp:BoundColumn DataField="ViewCount" DataFormatString="{0:#,###}" HeaderText="Views" ItemStyle-HorizontalAlign="Center" /><asp:BoundColumn DataField="SubmittedByName" HeaderText="Author" /><asp:BoundColumn DataField="SubmittedByEmail" HeaderText="Author's Email" /><asp:BoundColumn DataField="DateEntered" HeaderText="Date Added"DataFormatString="{0:MM-dd-yyyy}" /> </Columns></asp:datagrid>


如上例所示,上述代码指定了需要显示的特定列并且应用了特定的格式。请注意DataFormateString看上去很有趣。它的格式始终是{0:format string}。{0: …}指定通过格式化字符串(由…指定的)来格式化第一个参数(第一个参数指由DataReader返回的那个特定列的值)。在示例中我使用了格式化字符串#,###,它在每3个数字前加上一个逗号;格式化字符串MM-dd-yyyy指定通过月、日和年的格式显示日期/时间字段。


结论


花一些时间看一下第一个示例(见DataGrid Web控件深度历险(1))和现在的示例。改进确实很大!请注意所有这些样式和用户界面的改进不需要写一行代码就可实现。我们只是在Web控件的标记中设定了一些属性!事实上如果你正在使用类似Visual Studio .Net的编辑器, 你可通过点击一些按钮、选中一些复选框、选择列表框的一些项来设定格式化选项。想象一下在传统ASP中实现同样效果需要编写的那些冗长代码,那会使你爱上ASP.Net,如果你现在还没有的话。