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

Please rate and post your comments.
Thank You!

Sr KarthigaPosted Jul 7, 2016, 7:04 AM
Good one
Mukesh KumarPosted Oct 18, 2015, 2:58 PM
Good Job
Upendra Pratap ShahiPosted Jun 12, 2015, 1:07 AM
nice..
srikanth kumarPosted Dec 1, 2011, 1:25 AM
Thanks for sharing ..
Madhu BPosted Aug 4, 2011, 7:11 AM
1.I want examples on dependency Proparties? can any body help me.
Madhu BPosted Aug 4, 2011, 7:09 AM
Its Very Nice
surender bhyanPosted Jun 3, 2011, 2:33 PM
thanks a lot:)
Vijay YadavPosted Mar 3, 2011, 12:51 AM
Hi suthish, Thanks for sharing!!!!
Reeta Singh LodhiPosted Mar 2, 2011, 10:51 PM
Thanks for sharing
Suthish NairPosted Oct 15, 2010, 11:56 AM
remove the reference using System.Linq;
sourabh aggarwalPosted Oct 15, 2010, 7:14 AM
i am facing error Error The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?) so please help to rectify it