如何在GridView RowDataBound DataRow中设置列格式

时间:2015-09-30 11:24:59

标签: vb.net gridview

我有一个GridView,在我的RowDataBound事件中,我试图将列的格式设置为“dd MMM yyyy”。我首先检查RowType是否为DataRow,我的代码如下所示:

        If e.Row.RowType = System.Web.UI.WebControls.DataControlRowType.DataRow Then
        Dim ColCount As Integer
        ColCount = e.Row.Cells.Count

        For looper = 0 To ColCount - 1

            Dim cell As TableCell = e.Row.Cells(looper)
            ' For now I have hardcoded the Table Name
            Dim TempTabName As String = "STAFF"
            Dim TempColName As String
            Dim TempColType As String

            Dim CurrCol As BoundField = DirectCast(DirectCast(e.Row.Cells(looper), DataControlFieldCell).ContainingField, BoundField)
            ' Extracting Column Name
            TempColName = CurrCol.HeaderText
            ' Extracting Column Type (varchar, datetime etc)
            TempColType = GetColType(TempTabName, TempColName)

            ' Depending on Column Type Set Format
            ' Depending on Column Type Set Format
            Select Case TempColType
                Case "varchar"
                    status.Text = "We are at varchar"
                Case "nvarchar"
                    status.Text = "We are at nvarchar"
                Case "char"
                    status.Text = "We are at char"
                Case "datetime"
                    status.Text = "We are at datetime"
                    CurrCol.DataFormatString = "{0:dd/MM/yy}"                    
                Case "date"
                    status.Text = "We are at date"
                Case "time"
                    status.Text = "We are at time"
                Case "float"
                    status.Text = "We are at float"
            End Select
        Next
    End If

当我在线CurrCol.DataFormatString上运行此代码时,我收到错误“System.Web.dll中发生类型'System.NotSupportedException'的异常,但未在用户代码中处理”。附加信息:不支持指定方法

有人可以告诉我我做错了什么吗?或者有人可以用一些示例代码解释如何实现相同的目标吗?

1 个答案:

答案 0 :(得分:0)

您可以在Gridview HTML标记中指定设置日期格式。

如果您使用itemTemplate,那么您的示例代码就像

  <asp:GridView ID="GridView1" runat="server">
    <Columns>
    <asp:TemplateField>
      <ItemTemplate>
           <asp:Label 
           ID="Label1" 
           runat="server" 
           Text='<%# DataBinder.Eval(Container.DataItem, "date_of", "{0:dd MMM yyyy}") %>'>
        </asp:Label> 
      </ItemTemplate>
    </asp:TemplateField>
    </Columns> 
</asp:GridView>

此处date_of如果是要格式化的列名