Harvint Raj
Harvint Raj

Reputation: 69

How do i get the dates for the whole month in a dropdown? C#

I need the dates to be in a dropdown format.

i have created something that'll display 3 days but i would like to create a loop for it and i am not sure how.

ListItem li = new ListItem(DateTime.Now.ToString("MMM/dd"), DateTime.Now.ToString("MMM/dd"));
            DropDownList1.Items.Add(li);
            DropDownList2.Items.Add(li);
            ListItem li2 = new ListItem(DateTime.Now.AddDays(-1).ToString("MMM/dd"), DateTime.Now.AddDays(-1).ToString("MMM/dd"));
            DropDownList1.Items.Add(li2);
            DropDownList2.Items.Add(li2);
            ListItem li3 = new ListItem(DateTime.Now.AddDays(-2).ToString("MMM/dd"), DateTime.Now.AddDays(-2).ToString("MMM/dd"));
            DropDownList1.Items.Add(li3);
            DropDownList2.Items.Add(li3);

i would like the dropdown to have the date for the whole month from current date.

Upvotes: 1

Views: 64

Answers (2)

akg179
akg179

Reputation: 1559

This should work for you:

var startDate = DateTime.Now.Date;
var numberOfDays = startDate.Subtract(startDate.AddMonths(-1)).Days;

for(int i = 0; i <= numberOfDays; i++)
{
    ListItem li = new ListItem(DateTime.Now.AddDays(-1*i).ToString("MMM/dd"), DateTime.Now.AddDays(-1*i).ToString("MMM/dd"));
    DropDownList1.Items.Add(li);
    DropDownList2.Items.Add(li);
}

Upvotes: 0

jefftrotman
jefftrotman

Reputation: 1114


var dtmCurrent = DateTime.Today;
var dtmLimit = dtmCurrent.AddMonths(-1);
while(dtmCurrent >= dtmLimit)
{
    ListItem li = new ListItem(dtm.ToString("MMM/dd"), dtm.ToString("MMM/dd"));
    DropDownList1.Items.Add(li);
    DropDownList2.Items.Add(li);
    dtmCurrent = dtmCurrent.AddDays(-1);
}

Upvotes: 2

Related Questions