Populate asp.net dropdownlist with number

2019-06-27 16:03发布

A simple query , i want to populate the dropdownlist with number starting from 17 to 90 , and the last number should be a string like 90+ instead of 90. I guess the logic will be using a for loop something like:

for (int a = 17; a <= 90; a++)
        {
            ddlAge.Items.Add(a.ToString());
        }

Also I want to populate the text and value of each list item with the same numbers. Any ideas?

6条回答
The star\"
2楼-- · 2019-06-27 16:27
for (int i = 17; i <= 90; i++)
{
    ddlAge.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlAge.Items.Insert(0, new ListItem("Select Age", "0")); //First Item
ddlAge.Items.Insert(ddlAge.Items.Count, new ListItem("90+", "90+")); //Last Item
查看更多
Root(大扎)
3楼-- · 2019-06-27 16:34
for (int i = 17; i < 90; i++)
{
    ddlAge.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlAge.Items.Add(new ListItem("90+", "90"));
查看更多
你好瞎i
4楼-- · 2019-06-27 16:35
for (int i = 0; i <=91; i++)
    {
        if (i == 0)
        {
            ddlAge.Items.Add("Select Age");
        }
        else if(i<=90)
        {
            ddlAge.Items.Add(i.ToString());
            i++;
        }
        else
        {
         ddlAge.Items.Add("90+");
        }
    }
查看更多
时光不老,我们不散
5楼-- · 2019-06-27 16:43
for (int a = 17; a <= 90; a++)
{
    ddlAge.Items.Add(new ListItem(a.ToString(), a.ToString()));
}
查看更多
姐就是有狂的资本
6楼-- · 2019-06-27 16:45

Try this:

for (int a = 17; a <= 90; a++)
{
    var i = (a == 90 ? a.ToString() + '+': a.ToString());
    ddlAge.Items.Add(new ListItem(i, i));
}
查看更多
欢心
7楼-- · 2019-06-27 16:47

This is easy enough. You need to instantiate the ListItem class and populate its properties and then add it to your DropDownList.

    private void GenerateNumbers()
    {
        // This would create 1 - 10
        for (int i = 1; i < 11; i++)
        {
            ListItem li = new ListItem();
            li.Text = i.ToString();
            li.Value = i.ToString();
            ddlAge.Items.Add(li);
        }
    }
查看更多
登录 后发表回答