我正在尝试使用日期填充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