Click here to Skip to main content
15,868,078 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to use for loop in drop down list box to fill the month days from 1-30 ?
Posted
Comments
Clifford Nelson 29-Aug-12 16:49pm    
You need to tell the people what technology you are using: WinForm, WPF, ASP.NET...
[no name] 29-Aug-12 17:47pm    
what I think, In all the technology loops are same.
Correct me if i am wrong.
[no name] 29-Aug-12 16:51pm    
You want someone to write a for loop for you? Seriously?
[no name] 29-Aug-12 17:47pm    
ya, its very funny question. peoples are answering as well.
[no name] 29-Aug-12 17:49pm    
If the month is 28 or 31 days month, then what will happened with you?

If "ddl" is the id of the dropdownlist use the code below:
C#
for (int i = 1; i < 31; i++)
  {
     ddl.Items.Add(i.ToString());
  }
 
Share this answer
 
Here is a sample code that fills the dropdown with the days of month based on current date.

C#
DateTime date = DateTime.Now;

 for (int i = 1; i <= DateTime.DaysInMonth(date.Year, date.Month); i++)
 {
     YourDropdownID.Items.Add(new ListItem(i.ToString(), i.ToString()));
 }
 
Share this answer
 
v4
Comments
Mohamed Mitwalli 30-Aug-12 4:04am    
5+
__TR__ 30-Aug-12 4:31am    
Thank you :)
Hey everyone,

@_TR__: Nice answer. My 5 :) But one small thing.

Since, the question is tagged "C# 4.0" here is an improved version of your solution.
C#
DateTime today = DateTime.Now;
int days = DateTime.DaysInMonth(today.Year, today.Month);
Enumerable.Range(1, days).ToList().ForEach(i => YourDropdownID.Items.Add(i));

Hope this helps, regards
 
Share this answer
 
Comments
Kuthuparakkal 30-Aug-12 1:05am    
good one my 5+
__TR__ 30-Aug-12 4:03am    
Good one. 5ed!
try this.
C#
private void FillMyDropDown()
{
int[] datearr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };

           int daysInMonthNumber = System.DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);
           object[] currArray = new object[daysInMonthNumber];
           Array.Copy(datearr, currArray, daysInMonthNumber);

           MyDropdownID.Items.AddRange(currArray);

}
 
Share this answer
 
v2
Comments
CodeHawkz 30-Aug-12 1:24am    
why would you need to define it an array and copy it? I know memory is freely available these days but this is using way too much memory for a simple problem.

1. You've defined an array >> Takes memory
2. New array object is created >> takes memory again
3. Array copy >> a loop is run inside the array to deep copy the contents to your liking
4. AddRange >> Another loop is run to add the items

Your code is highly unoptimized, If I am not wrong.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900