asp dropdownlist – add numbers 1-15 to list

Is there a way of adding the values 1-15 to an asp dropdownlist without having to do each one individually…

I currently have:

ddlAdults.Items.Insert(0, new listitem("1", "1"))
ddlAdults.Items.Insert(1, new listitem("2", "2"))
ddlAdults.Items.Insert(2, new listitem("3", "3"))
ddlAdults.Ite......

…etc but there has to be a better way.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

ddlAdults.DataSource = Enumerable.Range(1, 15)
ddlAdults.DataBind()

Method 2

For i As Integer = 1 To 15
    ddlAdults.Items.Add(new ListItem(i.ToString(), i.ToString()))
Next i

Method 3

for(int i=0;i<15;i++)
{
   ddlAdults.Items.Insert(i, new ListItem((i+1).toString(), (i+1).toString()));
}

Method 4

Use a loop?

Like for loop or a foreach loop.

http://en.wikipedia.org/wiki/For_loop

or http://en.wikipedia.org/wiki/Foreach

That should help u, as I dont know what language u’re programming in..

Method 5

//cmbDay.Items.Insert(0, new ListItem("1"));
//cmbDay.Items.Insert(1, new ListItem("2"));
//cmbDay.Items.Insert(2, new ListItem("3"));
//cmbDay.Items.Insert(3, new ListItem("4"));

for( i=0;i<15;i++)
    {
       cmbDay.Items.Insert(i,new ListItem(i.ToString()));
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x