用文本和值填充DropDownList [英] Populating a DropDownList with text and values

查看:68
本文介绍了用文本和值填充DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET Webforms中有一个下拉列表,我想计算某个年份是多少年前。

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

第一行中的2002年是当前年份-9并且必须是值,9是visibel的文本,它显示2002年以前。

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 

我希望5是预选的。我怎么做?首先,我不知道如何添加隐藏的值(例如,在Visibel 9中为2002)。

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());
        }
    }


推荐答案

您可以使用ListItem添加文本和值

You can use a ListItem to add a text and value

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

您可以选择以下选项

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()));
  }
}

这篇关于用文本和值填充DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆