设置上周的周一是VB.NET下降的默认值

时间:2014-05-26 09:41:16

标签: asp.net vb.net date drop-down-menu

我有一个下拉列表,我必须填写最后5个星期一,但我需要设置previos周的星期一设置为默认值

我有以下代码来创建过去5个星期一的列表

Public Sub GetMondays()
    'populate the dateselection with the last 5 mondays to show the week starting
    Dim dtMondays As New DataTable()
    dtMondays.Columns.Add("Date")
    Dim i As Integer = 1
    Dim count As Integer
    While (count < 5)
        Dim Day As DateTime = Today.AddDays(-i)
        If Day.DayOfWeek = 1 Then
            DateSelection.Items.Add(New ListItem(Format(Day, "dd/MMM/yyyy"), Day))
            count = count + 1
        End If
        i += 1
    End While
End Sub

如果今天是2014年5月26日,我会看到5月10日以及下拉列表中的以下完整列表:

19/05/2014 > Displayed
12/05/2014
05/05/2014
28/04/2014
21/04/2014

如果今天是2014年5月27日,我会看到5月10日以及下拉列表中的以下完整列表:

26/05/2014 > Displayed
19/05/2014 > This one should be displayed
12/05/2014
05/05/2014
28/04/2014

我需要的是按上述顺序保留订单,按照上面的下拉列表选择上一个星期一。

有关如何执行此操作的任何想法

由于

1 个答案:

答案 0 :(得分:1)

比较今天的周数和列表中的第一项

GetMondays()

Dim c As Calendar = DateTimeFormatInfo.CurrentInfo.Calendar
If c.GetWeekOfYear(Today, CalendarWeekRule.FirstDay, DayOfWeek.Monday) _
   = c.GetWeekOfYear(DateSelection.Items(0).Text, CalendarWeekRule.FirstDay, DayOfWeek.Monday) Then
     DateSelection.SelectedIndex = 1
 Else
     DateSelection.SelectedIndex = 0
 End If

如果周数相同(例如&#34; 27/05 / 2014&#34;&#34; 26/05 / 2014&#34;将具有相同的周数),则将选择更改为第二项( SelectedIndex = 1)

P.S。

您还可以尝试使用更高效的代码来填充列表。找不到星期一,它不需要在4周内每天列举一次。您只需要在上周一找到,然后您就可以使用AddDays(-7)来获得一周的回报。

'Dim count As Integer
'While (count < 5)
'    Dim Day As DateTime = (Today.AddDays(1)).AddDays(-i) 
'    If Day.DayOfWeek = 1 Then
'        'DateSelection.Items.Add(New ListItem(Format(Day, "dd/MMM/yyyy"), Day))
'        Console.WriteLine(Format(Day, "dd/MMM/yyyy"), Day)
'        count = count + 1
'    End If
'    i += 1
'End While

Dim Day As Date = Today.AddDays(-(Today.DayOfWeek - DayOfWeek.Monday))
For count As Integer = 1 To 4
    DateSelection.Items.Add(New ListItem(Format(Day, "dd/MMM/yyyy"), Day))
    Day = Day.AddDays(-7)
Next