【问题标题】:How to format a date column in a DataGrid from VB如何在 VB 中格式化 DataGrid 中的日期列
【发布时间】:2011-03-31 16:11:22
【问题描述】:

我有一个包含数据网格的 .aspx 文件:

<asp:DataGrid ID="Gifts"
AutoGenerateColumns="True"
runat="server" AllowSorting="True">
    </asp:DataGrid>

与其关联的 .aspx.vb 文件用一个数据网格对象填充它。

Protected WithEvents Gifts As System.Web.UI.WebControls.DataGrid
Public GiftData As DataTable
Gifts.DataSource = New DataView(GiftData)
Gifts.DataBind()

一切正常。但是我想用特定的日期格式格式化其中的一列。有没有办法在vb代码中做到这一点?我知道我可以在 .aspx 中通过指定 AutoGenerateColumns="False" 然后显式定义列来做到这一点,但我想在代码中做到这一点,因为它对我的应用程序有更多的未来证明。

【问题讨论】:

    标签: asp.net vb.net visual-studio-2008 datagrid dataview


    【解决方案1】:

    您可以在RowDataBound-Eventhandler 中执行此操作:

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
         If e.Row.RowType = DataControlRowType.DataRow Then
            'If the first column is a date
            e.Row.Cells(0).Text = String.Format("{0:D}", Date.Parse(e.Row.Cells(0).Text))
         End If
    End Sub
    

    如果您真的在使用旧的 DataGrid,它的工作原理几乎相同。使用 DataGrid 的 ItemDataBound-Event 代替。

    Protected Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
         If e.Item.ItemType = ListItemType.Item orelse e.Item.ItemType = ListItemType.AlternatingItem Then
            'If the first column is a date
            e.Item.Cells(0).Text = String.Format("{0:D}", Date.Parse(e.Item.Cells(0).Text))
         End If
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2022-06-22
      • 1970-01-01
      • 2016-12-07
      • 2016-12-07
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多