Thursday, 31 March 2011

Dynamically bind dropdown with months names


Introduction
Through this article, i will show to how to Bind item Dynamically to Dropdownlist in ASP.NET.
Implementation
Just place a drop downlist into your web page, then add  following code to bind items to dropdown list within the page load event.
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack )
        {
            DD_Monthbind();
        }
    }

    private void DD_Monthbind()
    {
        DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
        for (int i = 1; i < 13; i++)
        {       
            DropDownList1.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));       

        }
    }
}
 
 In above code, i just get the datetime format for the current culture, and then add month names to dropdown list.this is simple snippets, but most usefull.thank for reading.

2 comments:

  1. Sir, this is great article. But i want something other than this article. If possible please send me code. I want three dropdown. 1st one is for year which selected by textbox value like from textbox1 and textbox2 means from 1900 to 2050, 2nd dropdown is for month which is already made by your this article and 3rd dropdown is for days in month depending upon year and month. Example Like if i select year 2011 then month will be 12 and if February month is selected then no. Of days will show 28 not 29. If is it possible then sened me mail on mail id is rajivnayan7@gmail.com

    ReplyDelete