我有一个gridview事件OnRowDataBound事件处理程序,如下所示:
protected void MyGridviewEvent(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem == "Duration")
{
}
}
这将选择行中的相应列。我想改变那个单元格的格式。这个单元格包含一个TimeSpan,我想格式化它hh:mm。
这是怎么做到的?
感谢。
答案 0 :(得分:3)
GridViewRow.DataItem返回此行的基础数据源。我怀疑它是一个像 Duration 这样的字符串。通常它是DataRowView,您可以通过索引或名称访问数据列。要格式化时间跨度,您可以使用带有自定义ToString字符串的.net framework 4 format providers版本。在早期的框架中,您必须手动完成。
VB.Net示例(我希望你得到它,重要的部分是RowDataBound部分)
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
答案 1 :(得分:1)
尝试这样的事情
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));
}
}
其中e.Row.Cells [1]是“持续时间”列的索引。