Junior Tekkis
Junior Tekkis

Reputation: 27

Changing 12 hr to 24 hr format in datagridview

My table contains 24 hr format and i want to change it to 12 hr. This is the code i found but it is not working for me.

DataGridView1.Columns(2).DefaultCellStyle.Format = "hh:mm tt"

I get an error like this

enter image description here

Upvotes: 0

Views: 432

Answers (1)

Andrew Morton
Andrew Morton

Reputation: 25023

You can use the DataGridView.CellFormatting Event to add your own code to display the value.

I put a default DataGridView and a Button on a form and used this code:

Option Strict On
Option Infer On

Public Class Form1
    Public Class Datum
        Public Property Name As String
        Public Property TimeTaken As TimeSpan

        Public Sub New()
            ' Empty constructor
        End Sub

        Public Sub New(name As String, timeTaken As TimeSpan)
            Me.Name = name
            Me.TimeTaken = timeTaken
        End Sub

    End Class

    Private Sub dataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
        If e.ColumnIndex = 1 Then
            If e.Value IsNot Nothing Then
                Dim ts As TimeSpan = CType(e.Value, TimeSpan)
                If ts < TimeSpan.FromDays(1) Then
                    Dim hr = ts.Hours Mod 12
                    Dim ampm = If(ts.Hours < 12, "am", "pm")
                    If hr = 0 Then hr = 12
                    Dim mins = ts.Minutes
                    e.Value = $"{hr}:{mins:00} {ampm}"
                    e.FormattingApplied = True
                End If

            End If
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim data As New List(Of Datum)
        data.Add(New Datum("Shaggy", TimeSpan.FromMinutes(9)))
        data.Add(New Datum("Fred", TimeSpan.FromMinutes(99)))
        data.Add(New Datum("Daphne", TimeSpan.FromMinutes(725)))
        data.Add(New Datum("Wilma", TimeSpan.FromMinutes(999)))
        data.Add(New Datum("Scooby", TimeSpan.FromMinutes(9999)))

        DataGridView1.DataSource = data

    End Sub

End Class

To get:

DGV with custom formatting for one column

Upvotes: 1

Related Questions