【问题标题】:Loop through gridview and look if todays date is between the ones spesified in gridview遍历gridview并查看今天的日期是否在gridview中指定的日期之间
【发布时间】:2014-01-21 14:47:24
【问题描述】:

我有一个带有列(年(复选框))(开始),(结束)的网格视图。我想循环浏览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

【问题讨论】:

  • 是 Web 还是 Winforms? (datagridview 只是 Winform 的控制)

标签: vb.net date gridview datagridview


【解决方案1】:

是的,正如 Mych 所说,你可以使用 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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      相关资源
      最近更新 更多