Friday, March 16, 2012

populating asp:dropdownlist programmatically

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 AmesHi,

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

"amessimon" <amessimon@.hotmail.com> wrote in message
news:e1ZyKV4AEHA.744@.TK2MSFTNGP10.phx.gbl...
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
Hello Simon
"amessimon" <amessimon@.hotmail.com> schrieb im Newsbeitrag
news:e1ZyKV4AEHA.744@.TK2MSFTNGP10.phx.gbl...
> 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.

0 comments:

Post a Comment