sds5150 sds5150 - 7 months ago 90
Vb.net Question

VB.NET automatically populate DataGridView column cell with DateTime.Now

I have a VB.NET DataGridView that requires user input to fill Null Columns.
I have that functioning.
I want to have the date_time column populate with the current date/time when the other columns are not NULL. The goal being to have an accurate time attached to when the other cells were populated.

I expect that I can use a timer and monitor the cells not to be null and trigger the date/time being added but I am not sure how to code the date/time population to the cell.

Can anyone give me a push in the right direction?

Thanks

Answer

This should give you a good start:

Dim dateTimColumnIndex As Integer = 1 '(example number on my part)
Private Sub CellValueChanged(ByVal sender As Object, _
    ByVal e As DataGridViewCellEventArgs) _
    Handles DataGridView1.CellValueChanged
        If (e.ColumnIndex <> dateTimColumnIndex) Then
            For z As Integer = 0 To DataGridView1.ColumnCount -1
                 If DataGridView1.Item(z, e.RowIndex).Value Is Nothing Then
                    Return
                 End If
                DataGridView1.Rows(e.RowIndex).Cells(dateTimColumnIndex).Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
            Next
        End if

End Sub

Updated won't do anything until you change value of allDoneLoading to True

Dim allDoneLoading As Boolean = False
Dim dateTimColumnIndex As Integer = 1 '(example number on my part)
Private Sub CellValueChanged(ByVal sender As Object, _
    ByVal e As DataGridViewCellEventArgs) _
    Handles DataGridView1.CellValueChanged
    If allDoneLoading = True Then
        If (e.ColumnIndex <> dateTimColumnIndex) Then
            For z As Integer = 0 To DataGridView1.ColumnCount - 1
                If DataGridView1.Item(z, e.RowIndex).Value Is Nothing Then
                    Return
                End If
                DataGridView1.Rows(e.RowIndex).Cells(dateTimColumnIndex).Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
            Next
        End If
    End If
End Sub