Reputation:
I'm developing web-application, in this I want to add all months values on the client side browser in registration form.
I'm doing it manually by adding all months' values one-by-one. I want to know is it possible to add all months with by putting one for loop in my code or not.
Suggest me if it's possible.
Thanks
Upvotes: 1
Views: 12911
Reputation: 19963
This is one option...
for (int m = 1; m <= 12; m++)
{
dd.Items.Add(new ListItem(new DateTime(2000, m, 1).ToString("MMMM"), m));
}
UPDATE
I know the question has already been "correctly answered", but taking into account @Jamie's comment, I thought I would add an alternative using the same principle...
DateTime dt = new DateTime(2000, 1, 1);
for (int m = 0; m < 12; m++)
{
dd.Items.Add(new ListItem(dt.AddMonths(m).ToString("MMMM"), m));
}
Upvotes: 1
Reputation: 6667
Why do it in code at all? Just statically add the months in the aspx file:
<asp:DropDownList Id="ddlMonths" runat="server">
<asp:ListItem Text="January" Value="1" />
<asp:ListItem Text="February" Value="2" />
<asp:ListItem Text="March" Value="3" />
<asp:ListItem Text="April" Value="4" />
...
</asp:DropDownList>
Last time I checked, the months don't change very much! :)
Upvotes: 0
Reputation: 223422
Here you can do it without the loop:
List<string> months = new List<string>() { "January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
dropDownList1.DataSource = months;
dropDownList1.DataBind();
Or if you insist on using loop:
List<string> months = new List<string>() { "January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
foreach (string month in months)
{
dropDownList1.Items.Add(month);
}
Upvotes: 5
Reputation: 29000
try with this code
foreach (string name in nameList)
{
ddl.Items.Add(new ListItem(name));
}
Upvotes: 1