populating asp:dropdownlist programmatically

A

amessimon

I need to display a drop down list which holds up to 250 listitems.

I'd like to create this programmatically rather than have to hardcode it
into the page.

For example

<asp:DropDownList id="numYears" runat="server" name="numYears">
<asp:ListItem Value="0" Text="0 years" Selected="true" />
<asp:ListItem Value="1" Text="1 year"/>
<asp:ListItem Value="2" Text="2 year"/>
<asp:ListItem Value="2" Text="2 year"/>
<asp:ListItem Value="3" Text etc............. up to 250 years

Thanks in advance..

Simon Ames
 
T

Teemu Keiski

Hi,

put the DDL declaration at the Page (or create it in code just as you see
better).

<asp:DropDownList ID="ddl1" Runat="server">
</asp:DropDownList>

Then say in Page_Load:

= = =
if(!Page.IsPostBack)
{
for(int i=0;i<251;i++)
{
ListItem litem=new ListItem(i.ToString() + " years",i.ToString());
ddl1.Items.Add(litem);
}
ddl1.SelectedIndex =0;
}
= = =

--
Teemu Keiski
MCP, Microsoft MVP (ASP.NET), AspInsiders member
ASP.NET Forum Moderator, AspAlliance Columnist



I need to display a drop down list which holds up to 250 listitems.

I'd like to create this programmatically rather than have to hardcode it
into the page.

For example

<asp:DropDownList id="numYears" runat="server" name="numYears">
<asp:ListItem Value="0" Text="0 years" Selected="true" />
<asp:ListItem Value="1" Text="1 year"/>
<asp:ListItem Value="2" Text="2 year"/>
<asp:ListItem Value="2" Text="2 year"/>
<asp:ListItem Value="3" Text etc............. up to 250 years

Thanks in advance..

Simon Ames
 
S

Simon Gorski

Hello Simon
amessimon said:
I need to display a drop down list which holds up to 250 listitems.

I'd like to create this programmatically rather than have to hardcode it
into the page.

For example

<asp:DropDownList id="numYears" runat="server" name="numYears">
<asp:ListItem Value="0" Text="0 years" Selected="true" />
<asp:ListItem Value="1" Text="1 year"/>
<asp:ListItem Value="2" Text="2 year"/>
<asp:ListItem Value="2" Text="2 year"/>
<asp:ListItem Value="3" Text etc............. up to 250 years

for (int i=0; i<=250; i++)

{

numYears.Items.Add(i.ToString());

}

mfg simon g.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top