none
How to convert listbox items to date and compare with calendar and bold affected date RRS feed

  • Question

  • Am having some difficulties with converting listbox dates (having the format dd-MM-yyyy) to datetime which i want to compare with monthcalendar date and instruct vb to bolden those dates on the calendar. Below is the novice quote i was trying to use to solve this. I get the following error when i tried running the code "Unable to cast object of type 'ObjectCollection' to type 'System.IConvertible'". I hope professionals on this platform will help me solve this. Thanks.


    For Each item In ListBoxDates.Items

    Dim listdate As DateTime = Convert.ToDateTime(ListBoxDates.Items)

    Dim eventdates() As Date = New Date() {convertdate}

    MonthCalendarEvents.BoldedDates = eventdates

    Next



    • Edited by Rans-Yaw Friday, November 16, 2018 5:35 PM
    Friday, November 16, 2018 5:33 PM

Answers

  • A simple approach would be to load the ListBox using a class instance as shown below where what is displayed is done via .ToString override. Here I created items via a range.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            MonthCalendarEvents.BoldedDates =
                CType(ListBoxDates.DataSource, List(Of Item)).
                    Select(Function(d) d.DateTime).ToArray
        End Sub
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim startDate = Now
            Dim endDate = Now.AddDays(10)
    
            ListBoxDates.DataSource = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days).
                Select(Function(offset) New Item With {.DateTime = startDate.AddDays(offset)}).ToList
        End Sub
    End Class
    Public Class Item
        Public Property DateTime As DateTime
        Public Overrides Function ToString() As String
            Return DateTime.ToString("dd-MM-yyyy")
        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 Rans-Yaw Friday, November 16, 2018 8:25 PM
    Friday, November 16, 2018 7:49 PM
    Moderator
  • Hi

    Here is an alternative. I had this ready to post but held off as Karen was taking care of it - however, it is burning a hole in my HDD so I have to post it.

    Takes care of malformed/non-date list items (by emboldening Today - which can easily be removed)

    Image

    Code

    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.Items.AddRange({"27-11-2018", "ERROR", "1-2-2019", "23-12-2018", "20-11-2018", "NOT A DATE", "26-1-2018", "7-11-2018", "1-1-2019", "3-2-2019", "STRING", "24 Jan 2019", "20/2/2019", 23.45})
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MonthCalendarEvents.BoldedDates = GetDates()
      End Sub
      Function GetDates() As Date()
        Dim dates As New List(Of Date)
        Dim d As Date
        For Each s As String In ListBox1.Items
          If Date.TryParse(s, d) Then
            dates.Add(d)
          Else
            dates.Add(Now.Date)
          End If
        Next
        Return dates.ToArray
      End Function
    End Class


    Regards Les, Livingston, Scotland

    • Marked as answer by Rans-Yaw Saturday, November 17, 2018 6:04 PM
    Saturday, November 17, 2018 12:38 AM

All replies

  • You are trying the convert the collection of Items.

    Use your item from your For Each loop to start:

    For Each item In ListBoxDates.Items
         Dim listdate As DateTime = Convert.ToDateTime(item)
         Dim eventdates() As Date = New Date() {convertdate}
    
         MonthCalendarEvents.BoldedDates = eventdates
    Next


    Friday, November 16, 2018 5:50 PM
  • Thanks Cyrille.

    After effecting your suggestion vb.net now finds this error 'String was not recognized as a valid DateTime' on this line of code: Dim listdate As DateTime = Convert.ToDateTime(item)

    What do you think might be the problem? Is there a way i can convert the listbox items to be seen as valid datetime by vb.net? Thanks.


    • Edited by Rans-Yaw Friday, November 16, 2018 6:16 PM
    Friday, November 16, 2018 6:12 PM
  • To start with you need to access the value for the item... sorry about, that but try:

    For Each item In ListBoxDates.Items
         Dim listdate As DateTime = Convert.ToDateTime(item.subitem(0).Text)
         Dim eventdates() As Date = New Date() {convertdate}
    
         MonthCalendarEvents.BoldedDates = eventdates
    Next

    It depends on your listBoxDates structure... is the date in the first column (0) or another one?

    Also have a look at TryParse for DateTime:

    For Each item In ListView1.Items
                Dim aDate As DateTime
                If DateTime.TryParse(item.subitems(1).Text, aDate) = True Then
                 ' Do something with aDate
               else
                 ' Do error management for that item
                End If
                Debug.Print(Convert.ToDateTime(item.subitems(1).Text))
            Next



    Friday, November 16, 2018 6:31 PM
  • Thanks again Cyrille,

    I appreciate your help. After trying both suggestions, they all ironically give the same error feedback (Public member 'subitem' on type 'String' not found) on each of the lines of code below:

    Dim listdate As DateTime = Convert.ToDateTime(item.subitem(0).Text)

    and

       If DateTime.TryParse(item.subitems(1).Text, aDate) = True Then

    I tried changing the subitem(0) to subitem(1) but it was the same error. The listbox currently has only two dates populated on it in the format dd-MM-yyyy.

    What do you think the problem might be. Thanks again.

    Friday, November 16, 2018 7:10 PM
  • A simple approach would be to load the ListBox using a class instance as shown below where what is displayed is done via .ToString override. Here I created items via a range.

    Public Class Form1
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            MonthCalendarEvents.BoldedDates =
                CType(ListBoxDates.DataSource, List(Of Item)).
                    Select(Function(d) d.DateTime).ToArray
        End Sub
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim startDate = Now
            Dim endDate = Now.AddDays(10)
    
            ListBoxDates.DataSource = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days).
                Select(Function(offset) New Item With {.DateTime = startDate.AddDays(offset)}).ToList
        End Sub
    End Class
    Public Class Item
        Public Property DateTime As DateTime
        Public Overrides Function ToString() As String
            Return DateTime.ToString("dd-MM-yyyy")
        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 Rans-Yaw Friday, November 16, 2018 8:25 PM
    Friday, November 16, 2018 7:49 PM
    Moderator
  • Karen Payne. Sorry, if this might be rude to you but the only thing i would say is I LOVE You...You've made my day!. I will try it when i get home.

    Not forgetting Cyrille, thanks for your lead.

    Friday, November 16, 2018 8:39 PM
  • I just realized something. The dates you used are in series where as the date i would be using will be random (ie. they are all not located within one month on the calendar) and also not even in series or succession.


    What do you think might be the possible problem especially when it gets to the computation section as seen below.

    ListBoxDates.DataSource = Enumerable.Range(0, 1 + endDate.Subtract(startDate).Days). Thanks.


    Friday, November 16, 2018 8:39 PM
  • Random works too :-)

    ListBoxDates.DataSource = New List(Of Item) From
        {
            New Item With {.DateTime = Now.AddDays(1)},
            New Item With {.DateTime = Now.AddDays(3)},
            New Item With {.DateTime = Now.AddDays(-30)}
        }


    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

    Friday, November 16, 2018 8:47 PM
    Moderator
  • Karen Payne, am here again. I would like to know if in a situation where the listbox has already been populated with the dates (.tostring) and not through the datasource. How can MonthCalendarEvents.BoldedDates still work? Any suggestion? Thanks.
    Friday, November 16, 2018 10:48 PM
  • Karen Payne, am here again. I would like to know if in a situation where the listbox has already been populated with the dates (.tostring) and not through the datasource. How can MonthCalendarEvents.BoldedDates still work? Any suggestion? Thanks.
    Well thinking about it, a lot more code. What I provided is what I would do and I like to keep things clean, efficient and not prone to errors.

    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

    Friday, November 16, 2018 11:31 PM
    Moderator
  • Here is what you asked for but note if a item in the ListBox can't be converted the code will throw an exception unlike my first recommendation.

    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            ListBox1.Items.AddRange(New String() {
                "02-11-2018",
                "13-11-2018",
                "22-11-2018",
                "24-12-2018"
            })
        End Sub
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            MonthCalendarEvents.BoldedDates = ListBox1.Items.Cast(Of String).
                Select(Function(value) Date.ParseExact(value, {"dd-MM-yyyy"},
                    Globalization.DateTimeFormatInfo.InvariantInfo,
                        Globalization.DateTimeStyles.None)).ToArray()
        End Sub
    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

    Saturday, November 17, 2018 12:02 AM
    Moderator
  • Hi

    Here is an alternative. I had this ready to post but held off as Karen was taking care of it - however, it is burning a hole in my HDD so I have to post it.

    Takes care of malformed/non-date list items (by emboldening Today - which can easily be removed)

    Image

    Code

    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ListBox1.Items.AddRange({"27-11-2018", "ERROR", "1-2-2019", "23-12-2018", "20-11-2018", "NOT A DATE", "26-1-2018", "7-11-2018", "1-1-2019", "3-2-2019", "STRING", "24 Jan 2019", "20/2/2019", 23.45})
      End Sub
      Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MonthCalendarEvents.BoldedDates = GetDates()
      End Sub
      Function GetDates() As Date()
        Dim dates As New List(Of Date)
        Dim d As Date
        For Each s As String In ListBox1.Items
          If Date.TryParse(s, d) Then
            dates.Add(d)
          Else
            dates.Add(Now.Date)
          End If
        Next
        Return dates.ToArray
      End Function
    End Class


    Regards Les, Livingston, Scotland

    • Marked as answer by Rans-Yaw Saturday, November 17, 2018 6:04 PM
    Saturday, November 17, 2018 12:38 AM

  • Thanks. I really appreciate your help.


    • Edited by Rans-Yaw Saturday, November 17, 2018 6:11 PM
    Saturday, November 17, 2018 6:11 PM
  • Your code did aid me very much to understand these arrays.

    I would like to find out how you set the date format for your monthcalender control. Am struggling with setting it to the format as yours (dd-MM-yyyy) from the default (MM-dd-yyyy). I don't seems to find the custom format on controls property section.

    Saturday, November 17, 2018 6:15 PM
  • Your code did aid me very much to understand these arrays.

    I would like to find out how you set the date format for your monthcalender control. Am struggling with setting it to the format as yours (dd-MM-yyyy) from the default (MM-dd-yyyy). I don't seems to find the custom format on controls property section.

    Hi

    Are you replying to my post?

    Your original post says '(having the format dd-MM-yyyy)', do  you want to use the mm-dd-yyy instead?


    Regards Les, Livingston, Scotland


    • Edited by leshay Saturday, November 17, 2018 7:58 PM
    Saturday, November 17, 2018 6:42 PM
  • Your code did aid me very much to understand these arrays.

    I would like to find out how you set the date format for your monthcalender control. Am struggling with setting it to the format as yours (dd-MM-yyyy) from the default (MM-dd-yyyy). I don't seems to find the custom format on controls property section.

    If you look over my code I show this but that does not apply to the calendar.

    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

    Sunday, November 18, 2018 12:54 AM
    Moderator