show selected date from calendar control in listbox

mcfly

Well-known member
Joined
Jun 15, 2009
Messages
54
Programming Experience
Beginner
Hi there,

I have a listbox control and a calendar control, when ever a user selects the date in the calendar control i want the listview to also highlight this date IF its in the listbox?...I am new to this and I my code below is logically very wrong, its causing an infinite Loop I think, any one any ideas...?

VB.NET:
Dim get_selected_date As Date

        'get selected date from calendar
        get_selected_date = MonthCalendar1.SelectionRange.Start

        'highlight the seleceted date in the listview1 if it's there
        Dim i As Integer
        i = 1
        Do While ListBox1.Items(i) > 0
            If ListBox1.Items(i) = get_selected_date Then
                ListBox1.SelectedItem.Equals(get_selected_date)
                'turn off loop
                i = -1
            End If
            'increment counter
            i = i + 1
        Loop
 
For MonthCalendar DateChanged event handler (default event):
VB.NET:
Me.ListBox1.SelectedIndex = Me.ListBox1.FindString(e.Start.ToShortDateString)
 
trying it the other way around, getting the calendar to highlight a date from a date selected in the listview, why doesn't this work:


VB.NET:
 Private Sub ListBox1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.Click

 Me.MonthCalendar1.SelectionStart = New Date(Me.ListBox1.SelectedItem)

 End Sub
 
New Date(Me.ListBox1.SelectedItem)
Do you see any constructor here that accept a String parameter: DateTime Constructor (System) (no there isn't)
Converting from a string value to another base type usually means some kind of translation called parsing, Date has several methods available for this (just look through the Methods list). Since all the values here was already Date values converted to strings it should be safe to call the Date.Parse method: DateTime.Parse Method (System)

This code sample is for SelectedIndexChanged event:
VB.NET:
If Me.ListBox1.SelectedItem IsNot Nothing Then
    Me.MonthCalendar1.SelectionStart = Date.Parse(CStr(Me.ListBox1.SelectedItem))       
End If
The reason code check first that item isn't Nothing is because that is the value when no item is selected, and Parse method would have problems trying to convert an empty string to Date.
 
A little correction, I somehow missed to update code when writing the post to this:
VB.NET:
Me.MonthCalendar1.SetDate(Date.Parse(CStr(Me.ListBox1.SelectedItem)))
When a Date was already selected setting a new SelectionStart causes the SelectionRange to expand. Using SetDate makes only that Date selected.
 
Back
Top