循环浏览gridview并查看今天的日期是否在gridview中指定的日期之间

时间:2014-01-21 14:47:24

标签: vb.net date gridview datagridview

我有一个带有列的网格视图(年(复选框))(开始),(结束)。我想循环浏览gridview并查看今天日期的结束日期和开始日期,并突出显示它并选中复选框。

我尝试过/想过这样的事情:

Dim today As String = DateTime.Now
Dim column As DataColumn
For x As Integer = 0 To Me.grdFinYear.Rows.Count - 1
    If grdFinYear.Rows(x).Cells(1).Value.ToString = column.ColumnName Then
        ' lblActiveFinYear.Text = current fin year
        ' colunm.DefaultCellStyle.BackColor = Color.Red
    End If
    '
Next

2 个答案:

答案 0 :(得分:1)

是的,正如Mych所说yoy可以使用OnRowDataBound事件。以下是一个示例工作代码:

ASPX标记:

<asp:GridView ID="gvGrid" runat="server" OnRowDataBound="gvGrid_OnRowDataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox runat="server" ID="cbYear"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

后端代码:

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim items = New List(Of GridSomeItem)
        items.Add(New GridSomeItem() With
                  {.StartDate = Date.Now.AddMonths(-2),
                   .EndDate = Date.Now.AddDays(-5)
                  })
        items.Add(New GridSomeItem() With
                  {.StartDate = Date.Now.AddDays(-10),
                   .EndDate = Date.Now.AddDays(10)
                  })
        items.Add(New GridSomeItem() With
                  {.StartDate = Date.Now.AddDays(-20),
                   .EndDate = Date.Now.AddDays(-10)
                  })

        gvGrid.DataSource = items
        gvGrid.DataBind()

    End Sub


    Protected Sub gvGrid_OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.DataItem Is Nothing Then
            Return
        End If

        Dim item As GridSomeItem = e.Row.DataItem
        Dim today As Date = Date.Now

        If today > item.StartDate And today < item.EndDate Then
            e.Row.BackColor = Drawing.Color.Red
            Dim cbYear As CheckBox = e.Row.FindControl("cbYear")

            cbYear.Checked = True

        End If

    End Sub
End Class

Public Class GridSomeItem
    Public Property StartDate As DateTime
    Public Property EndDate As DateTime
End Class

它只是数据绑定样本项并检查是否满足条件,然后更改Checkbox的颜色和值

答案 1 :(得分:0)

我通常使用RowDataBoundEvent来执行此操作,因为每行都绑定了它。检查行绑定是数据行而不是页眉或页脚。然后,您可以转到您感兴趣的列,如果条件匹配,您可以更改单元格的背景颜色。