VB.NET:用日期填充 Gridview(30 天间隔)

VB.NET : Populating Gridview with Dates (30 days interval)

我正在尝试用日期填充 gridview。

例如,今天的日期是 2/18/2019,30 天内的下一个日期是 3/20/2019。所以所需的输出应该是这样的

No.     Date
1       3/20/2019
2       4/19/2019
3       5/19/2019

等等

但结果是

No.     Date
1       3/20/2019
2       3/20/2019
3       3/20/2019

等等

到目前为止,这是我的代码。

Dim termCounter As Integer = 36
Dim today As DateTime = DateTime.Today
Dim dueDate As DateTime = today.AddDays(30)

Dim dtable As DataTable = New DataTable()
dtable.Columns.Add("No.")
dtable.Columns.Add("Payment Date")
Dim RowValues As Object() = {"", ""}
Dim dRow As DataRow

Dim tmpDate As Date
For i As Integer = 1 To termCounter
                    If GridAmortSched.RowCount <= 0 Then
                        RowValues(0) = i
                        RowValues(1) = dueDate.ToShortDateString
                        dRow = dtable.Rows.Add(RowValues)
                    Else
                        tmpDate = GridAmortSched.Rows(GridAmortSched.RowCount - 1).Cells(1).Value.ToString()
                        RowValues(0) = i
                        RowValues(1) = tmpDate.AddDays(30).ToShortDateString
                        dRow = dtable.Rows.Add(RowValues)
                    End If
                Next
                dtable.AcceptChanges()
                GridAmortSched.DataSource = dtable

通常情况下,代码会按照您告诉它的方式运行,而不是按照您希望的方式运行:-)。

每次执行循环时,都会从同一来源设置 tmpDate,然后在两行之后,将值放入 RowValues。 :

tmpDate = GridAmortSched.Rows(GridAmortSched.RowCount - 1).Cells(1).Value.ToString()

您没有通过 i 调整您的来源,也没有增加它。当您 AddDays 时,您也不会调整原始值(由于您分配它的方式和时间,这将不起作用)。

两个简单的修复(两个选项)

一个。 首先是根据循环值对要添加的天数进行索引 - 对下面的代码进行简单修改即可实现此目的。这是一个快速修复,将来可能更难维护 - 更重要的是,如果您更改循环起点等内容,则更难发现。

RowValues(1) = tmpDate.AddDays(30*i).ToShortDateString

二.另一种方案是解决代码逻辑问题。设置您的基线值,然后在循环内增加它。

Dim tmpDate As Date
tmpDate = GridAmortSched.Rows(GridAmortSched.RowCount - 1).Cells(1).Value.ToString() '*** Moved outside of loop
For i As Integer = 1 To termCounter
    If GridAmortSched.RowCount <= 0 Then
        RowValues(0) = i
        RowValues(1) = dueDate.ToShortDateString
        dRow = dtable.Rows.Add(RowValues)
    Else

        RowValues(0) = i
        tmpDate = tmpDate.AddDays(30) '*** Increment date every time it passes here
        RowValues(1) = tmpDate.ToShortDateString '*** Assign the new value
        dRow = dtable.Rows.Add(RowValues)
    End If
Next
dtable.AcceptChanges()
GridAmortSched.DataSource = dtable