user1487669
user1487669

Reputation:

adding values to the dropdownlist via loop in asp.net

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

Answers (4)

freefaller
freefaller

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

caveman_dick
caveman_dick

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

Habib
Habib

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

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

try with this code

foreach (string name in nameList)
{
    ddl.Items.Add(new ListItem(name));
}

Upvotes: 1

Related Questions