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?

6 Answers 6

7
for (int i = 17; i < 90; i++)
{
    ddlAge.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlAge.Items.Add(new ListItem("90+", "90"));
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

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.
i agree with @TimSchmelter , y check all the numbers .
@TimSchmelter you are correct, you answered it, so I'll leave mine AS IS.
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);
        }
    }

1 Comment

This only answers part of the question. OP wants the last item to show as 90+ instead of just 90
2
for (int a = 17; a <= 90; a++)
{
    ddlAge.Items.Add(new ListItem(a.ToString(), a.ToString()));
}

3 Comments

why you passing the number 2 times
It's setting the text and value.
You've forgotten to add 90+ as last item ;)
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.