如何从VB格式化DataGrid中的日期列

时间:2011-03-31 16:11:22

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

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

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

与之关联的.aspx.vb文件使用datagrid对象填充它。

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

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

1 个答案:

答案 0 :(得分: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 - 事件而已。

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