开发者

gridview cell formatting

I have a gridview event OnRowDataBound event handler like this:

protected void MyGridviewEvent(object sender, GridViewRowEventArgs e)
{
    if (e.Row.DataItem == "Duration")
    {

    }
}

This selects the appropriate column in the row. I'd like to change the format of that cell. This cell contains a开发者_如何学C TimeSpan and I'd like to format it hh:mm.

How's this done?

Thanks.


GridViewRow.DataItem returns the underlying datasource of this row. I doubt that it is a String like Duration. Normally it would be a DataRowView and you can access the datacolumn via index or name. To format a timespan you could use the .net framework 4 ToString version that takes a String with custom format providers. In earlier frameworks you have to do it manually.

VB.Net example(i hope you get it, the important part is the RowDataBound part)

 Private Sub BindGrid()
        Dim dt As New DataTable
        dt.Columns.Add("ID", GetType(Int32)).AutoIncrement = True
        dt.Columns.Add("Duration", GetType(TimeSpan))
        dt.PrimaryKey = New DataColumn() {dt.Columns("ID")}
        Dim newRow As DataRow = dt.NewRow
        newRow("ID") = 1
        newRow("Duration") = TimeSpan.FromDays(7)
        dt.Rows.Add(newRow)
        newRow = dt.NewRow
        newRow("ID") = 2
        newRow("Duration") = TimeSpan.FromMinutes(777)
        dt.Rows.Add(newRow)

        Me.GridView1.AutoGenerateColumns = True
        Me.GridView1.DataSource = dt
        Me.GridView1.DataBind()
    End Sub

    Private Sub GridRowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim row As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
            Dim duration As TimeSpan = DirectCast(row("Duration"), TimeSpan)
            e.Row.Cells(1).Text = String.Format("{0:00}:{1:00}", duration.TotalHours, duration.Minutes)
        End If
    End Sub


Try something like this

protected void MyGridviewEvent(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        TimeSpan ts = TimeSpan.Parse(DataBinder.Eval(e.Row.DataItem, "Duration").ToString());
        e.Row.Cells[1].Text = String.Format("{0:t}", ts));
    }
}

Where e.Row.Cells[1] is the index of the "Duration" column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜