How to format a date column in a DataGrid from VB

[亡魂溺海] 提交于 2019-12-12 22:55:06

问题


I have a .aspx file with a datagrid in it:

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

The .aspx.vb file associated with it fills it in with a datagrid object.

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

That all works fine. However I want to format one of the columns with a particular date format. Is there a way of doing that in the vb code? I know I can do it in the .aspx by specifing AutoGenerateColumns="False" and then explicitly defining the columns, but I want to do it in the code as it's more future proof for my application.


回答1:


You could do this in 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

If you're really using an old DataGrid, it works nearly the same. Use DataGrid's ItemDataBound-Event instead.

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


来源:https://stackoverflow.com/questions/5502918/how-to-format-a-date-column-in-a-datagrid-from-vb

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