Populating a DropDownList with text and values

2019-07-03 16:44发布

I have a dropdownlist in ASP.NET Webforms that I want to calculate how many years ago a certain year was.

In the first line 2002 is the current year -9 and has to be the value, and 9 is the text that is visibel and shows how many years ago 2002 was.

2002 9
2003 8
2004 7
2005 6
2006 5
2007 4
2008 3
2009 2
2010 1
2011 0 

And I want 5 to be the preselected. How Do I do that? First of I dont know how to add a hidden Value (ex. 2002 to the visibel 9).

This is my start... Not far, I know...

 {
        int CT = DateTime.Now.Year;
        int CT10 = CT - 10;

        for (int i = CT10; i <= CT; i++)

        {
            ddlBirthYear.Items.Add(i.ToString());
        }
    }

2条回答
一纸荒年 Trace。
2楼-- · 2019-07-03 17:05

You can use a ListItem to add a text and value

ddlBirthYear.Items.Add(new ListItem("text", "value"));

You can select that with

ddlBirthYear.SelectedValue = "5";

So your loop will look like this:

{
  int CT = DateTime.Now.Year;
  int CT10 = CT - 10;

  for (int i = CT10; i <= CT; i++)
  {
    ddlBirthYear.Items.Add(new ListItem(i.ToString(), (CT-i).ToString()));
  }
}
查看更多
Rolldiameter
3楼-- · 2019-07-03 17:21

After you've added your items just use the SelectedIndex property to preselect a value 5 years ago like so:

ddlBirthYear.SelectedIndex = 5;

SelectedIndex property is is pointing to an index of an item in the list.

If you want to select a particular year by it's value you need to use SelectedValue property.

ddlBirthYear.SelectedValue = "2008";
查看更多
登录 后发表回答