4

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?

Mr A
  • 6,448
  • 25
  • 83
  • 137

6 Answers6

7
for (int i = 17; i < 90; i++)
{
    ddlAge.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlAge.Items.Add(new ListItem("90+", "90"));
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
5

Try this:

for (int a = 17; a <= 90; a++)
{
    var i = (a == 90 ? a.ToString() + '+': a.ToString());
    ddlAge.Items.Add(new ListItem(i, i));
}
James Johnson
  • 45,496
  • 8
  • 73
  • 110
rs.
  • 26,707
  • 12
  • 68
  • 90
  • I don't want to be pedantic all the more on a competitive answer, but if i know that the only exception is the last item, why should i put the logic in the for loop at all? Simply add the exceptional item outside of the loop. That makes it also clearer. – Tim Schmelter May 04 '12 at 14:34
  • i agree with @TimSchmelter , y check all the numbers . – Mr A May 04 '12 at 14:35
  • @TimSchmelter you are correct, you answered it, so I'll leave mine AS IS. – rs. May 04 '12 at 14:36
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);
        }
    }
David East
  • 31,526
  • 6
  • 67
  • 82
2
for (int a = 17; a <= 90; a++)
{
    ddlAge.Items.Add(new ListItem(a.ToString(), a.ToString()));
}
Skorpioh
  • 1,355
  • 1
  • 11
  • 30
2
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
0
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+");
        }
    }