So far I've only posted a single post on this blog, which was the introduction to why I've started this blog...and I was way back in August. Very embarrasing! But now I've decided to get started. This small post is the solution to a very small but common task in webdevelopment: Dynamically generate the options in dropdown

Say you've a select in your page like this:

<select runat="server" id="ExpireYear" name="ExpireYear">
</select>

The contents of the select differs from time to time the page is loaded. I had a page which held a select box with the next 10 years in and of course I don't want the values of the option elements hardcoded in the code. Therefore I made a small Sub in my code behind which fills out the select box with option elements:

Private Sub GetYearOptions()
Dim mCurrentYear As Integer
Dim mShortYear As Integer
Dim i As Integer
Dim mListItem As UI.WebControls.ListItem
mCurrentYear = DatePart("yyyy", Now)
mShortYear = mCurrentYear - 2000 'I want 10 instead of 2010
For i = mShortYear To mShortYear + 9
mListItem = New UI.WebControls.ListItem(i, i)
ExpireYear.Items.Add(mListItem)
Next
End Sub

ExpireYear is the id of the select box and options are easily added by using ExpireYear.Items.Add(pListItem). The two parameters to the ListItem constructor is the text of the element and the value of the element.

I realize that this is a very trivial little post, but everyone has to start somewhere and hopefully this will be the start of better and better blog posts from me.

kick it on DotNetKicks.com