Reputation: 384
So basically what i want to get is a payment system for rental property.
I have made a database(in access for ease of work) and i'm now looking for a way to compare the date in the datagridview to today's date. If the date of the last payment is 30 days behind, it has to turn red. If its <30 it should stay green.
Now i'm wondering how to do that, because I can't seem to get it to work.
Since i'm fairly new to the vb.net-language I didn't get anything to work. I figured posting any code would be useless since it's all underlined with red and my program won't even run.
I figured it would be something in the style of
If me.dgv.columns("1") > 30:
me.dgv.row.defaultcellstyle.color = "red"
End if
The dates are sorted/displayed in an ascending fashion, not sure if that might help?
Any help would be of great value and I thank you in advance!
Upvotes: 0
Views: 357
Reputation: 827
From my experience it is best to handles this in RowPrePaint event.
Example:
Public Class Test
Private Shared Rnd As New Random
Private Sub FormControls_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Start Sample
DataGridView1.Columns.Add(New DataGridViewTextBoxColumn With {
.Name = "MyDate",
.ValueType = GetType(DateTime)})
For i As Integer = 0 To 1000
'create random dates in the past
DataGridView1.Rows.Add(Now.AddDays(-Rnd.Next(0, 25)))
Next
'End Sample
End Sub
Private Sub DataGridView1_RowPrePaint(sender As Object, e As DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
Dim DgvRow As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
With DgvRow
If DgvRow IsNot Nothing AndAlso DgvRow.Cells(0).Value IsNot Nothing AndAlso DgvRow.Cells(0).Value IsNot DBNull.Value Then
If Now.Subtract(CDate(DgvRow.Cells(0).Value)).TotalDays > 20 Then
DgvRow.DefaultCellStyle.BackColor = Color.Yellow
Else
DgvRow.DefaultCellStyle.BackColor = Color.Empty
End If
End If
End With
End Sub
End Class
Upvotes: 0
Reputation: 645
date.Now.addDays(30)
date.Now.addDays(-30)
to color the cell forecolor you use something like this:
For Each dr As DataGridViewRow In DataGridView1.Rows
If CDate(dr.Cells(0).Value) > Date.Now.AddDays(30) Then
dr.Cells(0).Style.ForeColor = Color.Red
End If
Next
you can also loop the cells to check all DGV cells for dates and compare them
Upvotes: 2