none
How to format Date Using DataGridView_CellContentClick Events?? RRS feed

  • Question

  •  Hi, EveryOne,

    With this sample of code I get  short Date (mm/dd/yyyy)  and Time (00:00:00) in textbox 

    Private Sub Dgw1_CellContentClick(sender As Object, e AsDataGridViewCellEventArgs) Handles Dgw1.CellContentClick
    Try
    If Dgw1.Rows.Count > 0 Then
    BirthDate = CDate(DataGridView1.CurrentRow.Cells(5).Value)
    frmInfo.ShowDialog()
    End If
    Catch ex As Exception
    MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error)
    End Try
    End Sub

    I want to get in text box Only the short Date (dd/mmm/yyyy) ,

    So i Try to use this code but i get this Error:The conversion of the string (15 / 00/ 1998) to date type is not valid

    Private Sub Dgw1_CellContentClick(senderAsObject,eAsDataGridViewCellEventArgs) Handles Dgw1.CellContentClick
    Try
    If Dgw1.Rows.Count > 0 Then
    BirthDate=CDate(DataGridView1.CurrentRow.Cells(5).Value).Date.ToString("mm / dd / yyyy")
    frmInfo.ShowDialog()
    End If
    Catch ex As Exception
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,MessageBoxIcon.Error)
    End Try
    End Sub

    I need your Help.

    Thank you very much.

               

    • Edited by Bajtitou Tuesday, March 27, 2018 12:17 PM
    Tuesday, March 27, 2018 8:03 AM

Answers

  • Hello,

    Took a few minutes a wrote up a quick demo using NorthWind Orders table. Using this code I got.

    Form code

    Imports BaseClasses
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ops As New DataOperations
            Dim items As List(Of OrderItem) = ops.Demo
            If ops.IsSuccessFul Then
                For Each orderitem In items
                    DataGridView1.Rows.Add(New Object() {orderitem.Id, orderitem.OrderDate})
                Next
            End If
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If Not DataGridView1.CurrentRow.IsNewRow Then
                Dim d As Date
                If Date.TryParse(DataGridView1.CurrentRow.Cells("Column2").Value.ToString, d) Then
                    MessageBox.Show(d.ToString("MM/dd/yyyy"))
                End If
            End If
        End Sub
    End Class
    

    Concrete class to return data

    Public Class OrderItem
        Public Property Id As Integer
        Public Property OrderDate As Date
    End Class
    

    Exception class

    Public Class BaseExceptionsHandler
        Protected mHasException As Boolean
        Public ReadOnly Property HasException() As Boolean
            Get
                Return mHasException
            End Get
        End Property
        Protected mHasSqlException As Boolean
        Public ReadOnly Property HasSqlException() As Boolean
            Get
                Return mHasSqlException
            End Get
        End Property
        Protected mLastException As Exception
        Public ReadOnly Property LastException() As Exception
            Get
                Return mLastException
            End Get
        End Property
        Public ReadOnly Property LastExceptionMessage As String
            Get
                Return mLastException.Message
            End Get
        End Property
    
        Public ReadOnly Property IsSuccessFul As Boolean
            Get
                Return Not mHasException OrElse Not mHasSqlException
            End Get
        End Property
    End Class

    Connection class

    Public Class BaseSqlServerConnections
        Inherits BaseExceptionsHandler
    
        Protected DatabaseServer As String = ".\SQLEXPRESS"
    
        Protected DefaultCatalog As String = "NorthWindAzure1"
        Public ReadOnly Property ConnectionString As String
            Get
                Return $"Data Source={DatabaseServer};" &
                       $"Initial Catalog={DefaultCatalog};Integrated Security=True"
            End Get
        End Property
    End Class

    Data class

    Imports System.Data.SqlClient
    Public Class DataOperations
        Inherits BaseSqlServerConnections
    
        Public Function Demo() As List(Of OrderItem)
            mHasException = False
    
            Dim items As New List(Of OrderItem)
    
            Dim selectStatement As String = "SELECT TOP 4 OrderID,OrderDate FROM dbo.Orders"
    
            Using cn = New SqlConnection(ConnectionString)
                Using cmd = New SqlCommand() With {.Connection = cn, .CommandText = selectStatement}
                    cn.Open()
                    Try
                        Dim reader = cmd.ExecuteReader
                        While reader.Read
                            items.Add(New OrderItem With
                                {
                                    .Id = reader.GetInt32(0),
                                    .OrderDate = reader.GetDateTime(1)
                                })
                        End While
                    Catch ex As Exception
                        mHasException = True
                    End Try
                End Using
            End Using
    
            Return items
    
        End Function
    
    End Class
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by Bajtitou Tuesday, March 27, 2018 8:21 PM
    Tuesday, March 27, 2018 2:02 PM
    Moderator
  • Hi

    Do you have any formatting of the DGV in your code (or, in the DGV properties) effecting the cells format?

    Your string as shown does convert to a valid date:

    Dim s As String = "1998/02/15" Dim d As DateTime = CDate(s)

    ' results in #2/15/1998 12:00:00 AM#

    So,you say the DataTable holds the correct string of that date, but the DGV holds the spurious /00/ month - how are you getting the data from the DataTable into the DGV?


    Regards Les, Livingston, Scotland


    • Edited by leshay Tuesday, March 27, 2018 7:12 PM
    • Marked as answer by Bajtitou Tuesday, March 27, 2018 8:18 PM
    Tuesday, March 27, 2018 6:23 PM
  • OK, if you use that in VB .Net it is converted to a DateTime format. Because it is date is the lowest value at that moment the first of january 1901 and is the time 00:00:00.

    The format of it in .Net is Int64, which value is a count (tick) from 100th nanoseconds starting at 1/1/1 0:0:0. 
    By the use of methods it can be represented as a string. For instance Tostring in that you can set the mask you want. 

    But AFAIK it has no default representation in the datagridview. That you can set in two ways. By filling the datagridview in the old fashion way which Karen shows,  but also by using the datasource. In that case you need the databindingevents. A sample about that we have on our website. 

    http://www.vb-tips.com/DataBindingEvents.aspx


    Success
    Cor


    • Edited by Cor Ligthert Tuesday, March 27, 2018 7:24 PM
    • Marked as answer by Bajtitou Tuesday, March 27, 2018 8:21 PM
    Tuesday, March 27, 2018 7:23 PM
  • Hi

    Do you have any formatting of the DGV in your code (or, in the DGV properties) effecting the cells format?

    Your string as shown does convert to a valid date:

    Dim s As String = "1998/02/15" Dim d As DateTime = CDate(s)

    ' results in #2/15/1998 12:00:00 AM#

    So,you say the DataTable holds the correct string of that date, but the DGV holds the spurious /00/ month - how are you getting the data from the DataTable into the DGV?


    Regards Les, Livingston, Scotland


    Hi,

    Yes I have , and this Formating who causes the exception ;

    Private Sub frmTestPonte_Load(sender As Object, e As EventArgs) HandlesMyBase.Load
    Dgw1.Columns(5).DefaultCellStyle.Format = "mmm/ dd / yyyy"
    End Sub

    Now the Problem is solved.

    So thank you very much  leshay

    At the end is there any way to show in text box only the short Date : 1998/02/15 without time

    I mean 00:00:00 (because now the text box show 1998/02/15 00:00:00).

    Best Regards , Bajtitou.



    Hi

    You can use something like this TextBox1.Text = MyDate.ToString("yyyy MM dd")

    *

    or, anything you want such as

    MyDate.ToString("yyyy MMM dd, ddd")


    Regards Les, Livingston, Scotland

    • Marked as answer by Bajtitou Tuesday, March 27, 2018 9:41 PM
    Tuesday, March 27, 2018 9:16 PM

All replies

  • Hello,

    Have you tried ToString("dd/mmm/yyyy") ?


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, March 27, 2018 9:14 AM
    Moderator
  •  Hi, EveryOne,

    With this sample of code I get  short Date (dd/mmm/yyyy)  and Time (00:00:00) in textbox 

    Private Sub Dgw1_CellContentClick(sender As Object, e AsDataGridViewCellEventArgs) Handles Dgw1.CellContentClick
    Try
    If Dgw1.Rows.Count > 0 Then
    BirthDate = CDate(DataGridView1.CurrentRow.Cells(5).Value)
    frmInfo.ShowDialog()
    End If
    Catch ex As Exception
    MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error)
    End Try
    End Sub

    I want to get in text box Only the short Date (dd/mmm/yyyy) ,

    So i Try to use this code but i get this Error:The conversion of the string (15 / 00/ 1998) to date type is not valid

    Private Sub Dgw1_CellContentClick(senderAsObject,eAsDataGridViewCellEventArgs) Handles Dgw1.CellContentClick
    Try
    If Dgw1.Rows.Count > 0 Then
    BirthDate=CDate(DataGridView1.CurrentRow.Cells(5).Value).Date.ToString("mm / dd / yyyy")
    frmInfo.ShowDialog()
    End If
    Catch ex As Exception
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK,MessageBoxIcon.Error)
    End Try
    End Sub

    I need your Help.

    Thank you very much.

               

    Hi

    And which month do you want the value 00 to represent?

    Since there is no such month, then the exception is correct.


    Regards Les, Livingston, Scotland

    Tuesday, March 27, 2018 12:12 PM
  • Hello,

    Have you tried ToString("dd/mmm/yyyy") ?


    Hi, Yes i tried it.

    Well, this is the Probleme;

    In the sql Table I have date in rows  like this : 1998/02/15 the month is /02/

    but in the datagridview it's like that:1988/00/15 the mont /00/ 

    the exception is here ,Why?

     thank you very much .

    Best Regards ,Bajtitou.

    Tuesday, March 27, 2018 12:46 PM

  • Hi

    And which month do you want the value 00 to represent?

    Since there is no such month, then the exception is correct.


    Regards Les, Livingston, Scotland

    Hi, Yes i tried it.

    Well, this is the Probleme;

    In the sql Table I have date in rows  like this : 1998/02/15 the month is /02/

    but in the datagridview it's like that:1988/00/15 the mont /00/ 

    the exception is here ,Why?

     thank you very much .

    Best Regards ,Bajtitou.


    Tuesday, March 27, 2018 12:48 PM
  • Hi

    The exception is correct.

    Before you click on the DGV column 5 to enter the event handler, what is showing in the cell - it must hold the 00 month value there?

    Knowing that the exception is correct, you need to look elsewhere in your code.


    Regards Les, Livingston, Scotland


    • Edited by leshay Tuesday, March 27, 2018 1:12 PM
    Tuesday, March 27, 2018 1:11 PM

  • In the sql Table I have date in rows  like this : 1998/02/15 the month is /02/


    You mean you have stored the dates in a char type and not in a date type?

    Because as in almost all current storage of dates it is done in ticks. (In SQL server with different tick and start time).

    Be aware likewise on the question, I cannot hammer a nail with my screwdriver, the answer is the same. Use the right tool. 


    Success
    Cor


    Tuesday, March 27, 2018 1:40 PM
  • Hello,

    Took a few minutes a wrote up a quick demo using NorthWind Orders table. Using this code I got.

    Form code

    Imports BaseClasses
    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ops As New DataOperations
            Dim items As List(Of OrderItem) = ops.Demo
            If ops.IsSuccessFul Then
                For Each orderitem In items
                    DataGridView1.Rows.Add(New Object() {orderitem.Id, orderitem.OrderDate})
                Next
            End If
        End Sub
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If Not DataGridView1.CurrentRow.IsNewRow Then
                Dim d As Date
                If Date.TryParse(DataGridView1.CurrentRow.Cells("Column2").Value.ToString, d) Then
                    MessageBox.Show(d.ToString("MM/dd/yyyy"))
                End If
            End If
        End Sub
    End Class
    

    Concrete class to return data

    Public Class OrderItem
        Public Property Id As Integer
        Public Property OrderDate As Date
    End Class
    

    Exception class

    Public Class BaseExceptionsHandler
        Protected mHasException As Boolean
        Public ReadOnly Property HasException() As Boolean
            Get
                Return mHasException
            End Get
        End Property
        Protected mHasSqlException As Boolean
        Public ReadOnly Property HasSqlException() As Boolean
            Get
                Return mHasSqlException
            End Get
        End Property
        Protected mLastException As Exception
        Public ReadOnly Property LastException() As Exception
            Get
                Return mLastException
            End Get
        End Property
        Public ReadOnly Property LastExceptionMessage As String
            Get
                Return mLastException.Message
            End Get
        End Property
    
        Public ReadOnly Property IsSuccessFul As Boolean
            Get
                Return Not mHasException OrElse Not mHasSqlException
            End Get
        End Property
    End Class

    Connection class

    Public Class BaseSqlServerConnections
        Inherits BaseExceptionsHandler
    
        Protected DatabaseServer As String = ".\SQLEXPRESS"
    
        Protected DefaultCatalog As String = "NorthWindAzure1"
        Public ReadOnly Property ConnectionString As String
            Get
                Return $"Data Source={DatabaseServer};" &
                       $"Initial Catalog={DefaultCatalog};Integrated Security=True"
            End Get
        End Property
    End Class

    Data class

    Imports System.Data.SqlClient
    Public Class DataOperations
        Inherits BaseSqlServerConnections
    
        Public Function Demo() As List(Of OrderItem)
            mHasException = False
    
            Dim items As New List(Of OrderItem)
    
            Dim selectStatement As String = "SELECT TOP 4 OrderID,OrderDate FROM dbo.Orders"
    
            Using cn = New SqlConnection(ConnectionString)
                Using cmd = New SqlCommand() With {.Connection = cn, .CommandText = selectStatement}
                    cn.Open()
                    Try
                        Dim reader = cmd.ExecuteReader
                        While reader.Read
                            items.Add(New OrderItem With
                                {
                                    .Id = reader.GetInt32(0),
                                    .OrderDate = reader.GetDateTime(1)
                                })
                        End While
                    Catch ex As Exception
                        mHasException = True
                    End Try
                End Using
            End Using
    
            Return items
    
        End Function
    
    End Class
    


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    • Marked as answer by Bajtitou Tuesday, March 27, 2018 8:21 PM
    Tuesday, March 27, 2018 2:02 PM
    Moderator
  • Karen,

    That won't go as he indicated he is using Char (string) as type to store his date. Northwind uses small date as far as I remember me.


    Success
    Cor


    Tuesday, March 27, 2018 2:52 PM
  • Karen,

    That won't go as he indicated he is using Char (string) as type to store his date. Northwind uses small date as far as I remember me.


    Success
    Cor


    Hi Cor,

    The OrderDate is DateTime

    I loaded the second column as a DataTime but note even so I converted it to a string and did the TryParse even though it was not needed simply so show if it was actually a string we can assert the string could be converted to a date time.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, March 27, 2018 3:27 PM
    Moderator

  • Karen,

    Don't do if I'm stupid. I know what is in Northwnd. I never used another sample database. (Unlucky enough because all dates in it are become very old).  Ken tryied another one from Microsoft and therefore you see that sometimes on our website. 

    This is what the OP wrote: "In the sql Table I have date in rows  like this : 1998/02/15"  this means a char (or string in .Net). 

    The problem is probably most that he/she does not know what a DateTime format is. 


    Success
    Cor



    Tuesday, March 27, 2018 5:16 PM
  • Hi

    The exception is correct.

    Before you click on the DGV column 5 to enter the event handler, what is showing in the cell - it must hold the 00 month value there?


    Hi,

    Yes , in DGV column 5 it is showing in the cell this : 1988/00/15 it hold  the 00 month  from ther ,

    but in my table the date in the same cell that : 1998/02/15 the month is /02/.

    So thank you very much.

    Best Regards , Bajtitou.

    Tuesday, March 27, 2018 6:13 PM

  • In the sql Table I have date in rows  like this : 1998/02/15 the month is /02/


    You mean you have stored the dates in a char type and not in a date type?


    Hi, 

    No , the date in the table is formated in Date not Datetime or char , and it is correct an it is showing like this: 1998/02/15 the month is /02/ but in DGV it is showing 1998/00/15 the month is /00/.

    So thank you very much.

    Best Regards , Bajtitou.

    Tuesday, March 27, 2018 6:21 PM
  • Hi

    Do you have any formatting of the DGV in your code (or, in the DGV properties) effecting the cells format?

    Your string as shown does convert to a valid date:

    Dim s As String = "1998/02/15" Dim d As DateTime = CDate(s)

    ' results in #2/15/1998 12:00:00 AM#

    So,you say the DataTable holds the correct string of that date, but the DGV holds the spurious /00/ month - how are you getting the data from the DataTable into the DGV?


    Regards Les, Livingston, Scotland


    • Edited by leshay Tuesday, March 27, 2018 7:12 PM
    • Marked as answer by Bajtitou Tuesday, March 27, 2018 8:18 PM
    Tuesday, March 27, 2018 6:23 PM

  • This is what the OP wrote: "In the sql Table I have date in rows  like this : 1998/02/15"  this means a char (or string in .Net). 

    The problem is probably most that he/she does not know what a DateTime format is. 




    Hi, 

     the Date format in the table is Date it is not Datetime or Char.

    Thank you.


    • Edited by Bajtitou Tuesday, March 27, 2018 6:59 PM
    Tuesday, March 27, 2018 6:58 PM
  • OK, if you use that in VB .Net it is converted to a DateTime format. Because it is date is the lowest value at that moment the first of january 1901 and is the time 00:00:00.

    The format of it in .Net is Int64, which value is a count (tick) from 100th nanoseconds starting at 1/1/1 0:0:0. 
    By the use of methods it can be represented as a string. For instance Tostring in that you can set the mask you want. 

    But AFAIK it has no default representation in the datagridview. That you can set in two ways. By filling the datagridview in the old fashion way which Karen shows,  but also by using the datasource. In that case you need the databindingevents. A sample about that we have on our website. 

    http://www.vb-tips.com/DataBindingEvents.aspx


    Success
    Cor


    • Edited by Cor Ligthert Tuesday, March 27, 2018 7:24 PM
    • Marked as answer by Bajtitou Tuesday, March 27, 2018 8:21 PM
    Tuesday, March 27, 2018 7:23 PM
  • OK, if you use that in VB .Net it is converted to a DateTime format. Because it is date is the lowest value at that moment the first of january 1901 and is the time 00:00:00.

    The format of it in .Net is Int64, which value is a count (tick) from 100th nanoseconds starting at 1/1/1 0:0:0. 
    By the use of methods it can be represented as a string. For instance Tostring in that you can set the mask you want. 

    But AFAIK it has no default representation in the datagridview. That you can set in two ways. By filling the datagridview in the old fashion way which Karen shows,  but also by using the datasource. In that case you need the databindingevents. A sample about that we have on our website. 

    http://www.vb-tips.com/DataBindingEvents.aspx


    Success
    Cor


    Indeed I showed the "incorrect" way to load a DataGridView which was intentional as it appeared to me they were not using .DataSource. I'm sure you know I dislike accessing data that is not set to a data source in a DataGridView :-)

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Tuesday, March 27, 2018 7:48 PM
    Moderator


  • Indeed I showed the "incorrect" way to load a DataGridView which was intentional as it appeared to me they were not using .DataSource. I'm sure you know I dislike accessing data that is not set to a data source in a DataGridView :-)


    Karen,

    If it is only for showing data, I won't call it incorrect (only a lot of work). It is a kind of default way for web pages. 

    But if you use it as well to update, I would not advice it. 

    :-)


    Success
    Cor

    Tuesday, March 27, 2018 8:12 PM
  • Hi

    Do you have any formatting of the DGV in your code (or, in the DGV properties) effecting the cells format?

    Your string as shown does convert to a valid date:

    Dim s As String = "1998/02/15" Dim d As DateTime = CDate(s)

    ' results in #2/15/1998 12:00:00 AM#

    So,you say the DataTable holds the correct string of that date, but the DGV holds the spurious /00/ month - how are you getting the data from the DataTable into the DGV?


    Regards Les, Livingston, Scotland


    Hi,

    Yes I have , and this Formating who causes the exception ;

    Private Sub frmTestPonte_Load(sender As Object, e As EventArgs) HandlesMyBase.Load
    Dgw1.Columns(5).DefaultCellStyle.Format = "mmm/ dd / yyyy"
    End Sub

    Now the Problem is solved.

    So thank you very much  leshay

    At the end is there any way to show in text box only the short Date : 1998/02/15 without time

    I mean 00:00:00 (because now the text box show 1998/02/15 00:00:00).

    Best Regards , Bajtitou.



    • Edited by Bajtitou Tuesday, March 27, 2018 8:27 PM
    Tuesday, March 27, 2018 8:18 PM
  • Hi

    Do you have any formatting of the DGV in your code (or, in the DGV properties) effecting the cells format?

    Your string as shown does convert to a valid date:

    Dim s As String = "1998/02/15" Dim d As DateTime = CDate(s)

    ' results in #2/15/1998 12:00:00 AM#

    So,you say the DataTable holds the correct string of that date, but the DGV holds the spurious /00/ month - how are you getting the data from the DataTable into the DGV?


    Regards Les, Livingston, Scotland


    Hi,

    Yes I have , and this Formating who causes the exception ;

    Private Sub frmTestPonte_Load(sender As Object, e As EventArgs) HandlesMyBase.Load
    Dgw1.Columns(5).DefaultCellStyle.Format = "mmm/ dd / yyyy"
    End Sub

    Now the Problem is solved.

    So thank you very much  leshay

    At the end is there any way to show in text box only the short Date : 1998/02/15 without time

    I mean 00:00:00 (because now the text box show 1998/02/15 00:00:00).

    Best Regards , Bajtitou.



    Hi

    You can use something like this TextBox1.Text = MyDate.ToString("yyyy MM dd")

    *

    or, anything you want such as

    MyDate.ToString("yyyy MMM dd, ddd")


    Regards Les, Livingston, Scotland

    • Marked as answer by Bajtitou Tuesday, March 27, 2018 9:41 PM
    Tuesday, March 27, 2018 9:16 PM
  • Hello,

    Took a few minutes a wrote up a quick demo using NorthWind Orders table. Using this code I got.

    Form code

    Hello,

    I test this code with Norhwind DB , it is working very well.

    thank you very much .

    Best Regards Bajtitou.


    Tuesday, March 27, 2018 10:11 PM