循环通过日期vb.net

时间:2015-08-28 04:29:32

标签: vb.net loops date datagridview

我想每天创建一个datagridview。到目前为止,这是我的代码。它没有显示任何错误,但是当我运行代码时,它只是加载表单,但dgv没有出现。我该怎么办?

   Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim start As Date = Date.Now
        Dim apocap As Date = Date.Parse(#8/22/2050#)
        Dim loopdate As Date = start

        While start < apocap
            Dim dgv As New DataGridView
            With dgv
                .Size = New Size(250, 250)
                .ColumnCount = 2
                .RowCount = 12
                .Location = New Point(12, 9)
                .Visible = True

            End With

            start = start.Date.AddDays(1)
        End While
    End Sub
End Class

1 个答案:

答案 0 :(得分:1)

您必须将它们添加到表单中。此外,您还要更改.Left和/或.Top.Location)属性,以便它们不会叠加在一起:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim start As DateTime = DateTime.Today
    Dim apocap As New DateTime(2050, 8, 22)   
    Dim i As Integer = 0

    While start < apocap
        Dim dgv As New DataGridView
        With dgv
            .Size = New Size(250, 250)
            .ColumnCount = 2
            .RowCount = 12
            .Location = New Point(12, (9 + (250 * i)))
            .Visible = True
        End With

        Me.Controls.Add(dgv)
        i += 1
        start = start.AddDays(1)
    End While
End Sub

为了好玩,我喜欢这样写:

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim start As DateTime = DateTime.Today
    Dim apocap As New DateTime(2050, 8, 22)
    Dim count As Integer = CInt((apocap - start).TotalDays)

    Me.Controls.AddRange(Enumerable.Range(0, count).Select(
       Function(i)
           Return New DataGridView With {
             .Size = New Size(250, 250),
            .ColumnCount = 21,
            .RowCount = 12,
            .Location = New Point(12, (9 + (250 * i))),
            .Visible = True
            }
            'start.AddDays(i) is there if you need it
       End Function
    ).ToArray())
End Sub
相关问题