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.DayNamesListItem 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.MonthNamesListItem 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, 3:04 AM EDT
Good one
Mukesh KumarPosted Oct 18, 2015, 10:58 AM EDT
Good Job
Upendra Pratap ShahiPosted Jun 11, 2015, 9:07 PM EDT
nice..
srikanth kumarPosted Nov 30, 2011, 8:25 PM EST
Thanks for sharing ..
Madhu BPosted Aug 4, 2011, 3:11 AM EDT
1.I want examples on dependency Proparties? can any body help me.
Madhu BPosted Aug 4, 2011, 3:09 AM EDT
Its Very Nice
surender bhyanPosted Jun 3, 2011, 10:33 AM EDT
thanks a lot:)
Vijay YadavPosted Mar 2, 2011, 7:51 PM EST
Hi suthish, Thanks for sharing!!!!
Reeta Singh LodhiPosted Mar 2, 2011, 5:51 PM EST
Thanks for sharing
Suthish NairTOP 100Posted Oct 15, 2010, 7:56 AM EDT
remove the reference using System.Linq;
sourabh aggarwalPosted Oct 15, 2010, 3:14 AM EDT
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