Search code examples
asp.netvb.netdatetimedatetime-formatdropdownbox

Load years in ASP.Net DropDownList


I need to fill my DropDownList with years but I'm struggling with it. I tried doing it for months and succeeded. The problem is I am having issues in calling the right methods for the DateTime object. Can somebody help me out?

Here is how I have loaded months in my DropDownList:

Sub LoadMonth()
     Try
         ddlMonth.Items.Clear()
         If ddlMonth.Items.Count = 0 Then
            For month As Integer = 1 To 12
                Dim monthName As String = DateTimeFormatInfo.CurrentInfo.GetMonthName(month)
                ddlMonth.Items.Add(New ListItem(monthName, month.ToString("00")))
            Next
        End If
        ddlMonth.Items.Insert(0, New ListItem("--Select--", 1))
    Catch ex As Exception

    End Try
End Sub

Solution

  • You can simply achieve it using a loop like:

      Dim i as integer
      for  i = 2008 to 2100
        ddlYear.Items.Add(i.ToString());
       next i 
      ddlYear.Items.FindByValue(System.DateTime.Now.Year.ToString()).Selected = true;  //set current year as selected
    

    hope this helps.