Populate asp.net dropdownlist with number

2019-06-27 16:26发布

问题:

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?

回答1:

for (int i = 17; i < 90; i++)
{
    ddlAge.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlAge.Items.Add(new ListItem("90+", "90"));


回答2:

Try this:

for (int a = 17; a <= 90; a++)
{
    var i = (a == 90 ? a.ToString() + '+': a.ToString());
    ddlAge.Items.Add(new ListItem(i, i));
}


回答3:

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


回答4:

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


回答5:

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


回答6:

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+");
        }
    }