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.
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
精彩评论