Automatic Binding of Days, Months, Years to a DropDownList Control

Introduction

This blog shows a simple snippet of automatic binding of Days, Months, Years to a DropDownList/ListBox control.

Below following methods were used for Binding.

1. Method for Binding days

System.DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month).

This method returns Total Days in a Month.

Method returns the last day of the month.

int daysInMonth = System.DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);

for (int i = 1; i <= daysInMonth; i++)
{
    ddle.Items.Add(i.ToString());
}

ddle.Items.Insert(0, "Select");

ddle.SelectedIndex = 0;

//ddle.Attributes.Add("size", "3");

2. Method for Binding DayNames

Doing a for-each loop to retrieve Day Names from.

DateTimeFormatInfo.CurrentInfo.DayNames
ListItem lc;
foreach (var item in DateTimeFormatInfo.CurrentInfo.DayNames)
{
    lc = new ListItem();
    lc.Text = item;
    lc.Value = item;
    dd11.Items.Add(lc);
}

dd11.Items.Insert(0, "Select");
dd11.SelectedIndex = 0;

for (int i = 0; i < dd11.Items.Count; i++)
{
    if (i == 2 || i == 4)
    {
        // Disable items at index 2 and 4
        dd11.Items[i].Attributes.Add("disabled", "disabled");
    }
    else
    {
        // Set the color to red for other items
        dd11.Items[i].Attributes.CssStyle.Add("color", "red");
    }
}

3. Method for binding MonthNames

Doing a for-each to retrieve Month Names from.

DateTimeFormatInfo.CurrentInfo.MonthNames
ListItem lc;

foreach (var item in DateTimeFormatInfo.CurrentInfo.MonthNames)
{
    if (!string.IsNullOrEmpty(item))
    {
        lc = new ListItem();
        lc.Text = item;
        lc.Value = item;
        dd12.Items.Add(lc);
    }
}

dd12.Items.Insert(0, "Select");
dd12.SelectedIndex = 0;

Some styling is also applied; you can uncomment those code and test the samples attached.

Output

image2.gif

Please rate and post your comments.

Thank You!


Similar Articles