Link to home
Start Free TrialLog in
Avatar of fwsteal
fwsteal

asked on

populate dropdownlist asp.net c# 2.0

I need to populate the following drop down list from the
code behind with year values that start at current year and
go up to 9 years in future.

<asp:DropDownList ID="ddlYear" runat="server" TabIndex="20">
  <asp:ListItem Value="2007">2007</asp:ListItem>
  <asp:ListItem Value="2008">2008</asp:ListItem>
  <asp:ListItem Value="2009">2009</asp:ListItem>
  <asp:ListItem Value="2010">2010</asp:ListItem>
  <asp:ListItem Value="2011">2011</asp:ListItem>
  <asp:ListItem Value="2012">2012</asp:ListItem>
  <asp:ListItem Value="2013">2013</asp:ListItem>
  <asp:ListItem Value="2014">2014</asp:ListItem>
  <asp:ListItem Value="2015">2015</asp:ListItem>                
</asp:DropDownList>


protected void Page_Load(object sender, EventArgs e)
 {
  if (!Page.IsPostBack)
   {
    //populate ddlYear
    PopulateYears();
   }
 }

protected void PopulateYears()
{
  //how to populate ddlYear

}
ASKER CERTIFIED SOLUTION
Avatar of alfredwhang
alfredwhang

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
hi,

ddlYear.Items.Add(new ListItem("2007","2007"));
or
ddlYear.Items.Add("2007");

b u d d h a

Avatar of fwsteal
fwsteal

ASKER

   protected void PopulateYears()
    {
        //populate ddlYear
        int yr = DateTime.Now.Year;
        for (int i = 0; i<=9;i++)
            {
                ddlYear.Items.Add(yr + i);
            }
    }

ddlYear - The best overloaded method match for 'System.Web.UI.WebControls.ListItemCollection.Add(string)' has some invalid arguments.

yr - Argument '1': cannot convert from 'int' to 'string'
Avatar of fwsteal

ASKER

       int yr = DateTime.Now.Year;
        for (int i = 0; i<=9;i++)
            {
                ddlYear.Items.Add((Convert.ToString(yr)) + i);
            }

produces:
20070
20071
etc
20079
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
fwsteal might you consider splitting points? thx.
Avatar of fwsteal

ASKER

oops; how do I achieve that? i think I clicked too fast
This is a solution for you:
protected void Page_Load(object sender, EventArgs e)
        {
            int yearStart = DateTime.Now.Year;
            if(!Page.IsPostBack)
            {
                for(int i=0;i<9;i++)
                {
                    this.Year_DropDownList.Items.Add(new ListItem((yearStart+i).ToString(),(yearStart+i).ToString()));
                }
            }
        }

Greetings,
Nguyen Xuan Huy