3

we can make dropdown list in asp.net component with below syntax

 <asp:DropDownList ID="test" runat="server">
      <asp:ListItem Text="1" Value="1"></asp:ListItem>
 </asp:DropDownList>

if we want our combo box contain 1 to 1000 , is there any way to populate it with foreach loop , rather than manually add 1000 item to it ?

0

6 Answers 6

5

Yes, you can add ListItems programmatically:

for(int i=1; i<=1000; i++)
{
    ListItem item = new ListItem(i.ToString(), i.ToString());
    test.Items.Add(item);
}

ListItemCollection.Add

You could also use this linq query and use it as DataSource:

var source = Enumerable.Range(1, 1000)
    .Select(i => new { Text= i.ToString(), Value=i.ToString() });
test.DataSource = source;
test.DataTextField = "Text";
test.DataValueField = "Value";
test.DataBind();
Sign up to request clarification or add additional context in comments.

Comments

1

How about just binding the dropdown list directly to a collection of numbers?

IEnumerable<int> numbers = Enumerable.Range(1, 1000);
test.DataSource = numbers;
test.DataBind();

Comments

1

Sure, in your code-behind:

if (!Page.IsPostBack)
{
    // Populate DropDownList
    for (int i = 1; i < 1001; i++)
    {
        ListItem li = new ListItem(i.ToString(),i.ToString());
        test.Items.Add(li);
    }
}

Comments

0
 for( int i=1;i<=100;i++)
 {
    ListItem li=new ListIem(i.ToString(),i.ToString());
    test.Items.add(li);
 }

Comments

0

Very basic code...

if(!Page.IsPostBack)
{
  for (int i = 1; i <= 1000; i++)
  {
    test.Items.Add(new ListItem(i.ToString(), i.ToString()));
  }
}

Comments

0

Here's some pseudocode:

for (int i = 0; i < 1000; i++)
{
    ListItem item = new ListItem();
    item.Text = i.ToString();
    test.Items.Add(item);
}

You will have to find out exactly how to create the ListItem and populate it with a value.

1 Comment

D'oh! Thanks for the nudge.

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.