C # Dropdowns 0 - 100 without adding each item?

Sorry if this is a stupid question ... I'm just trying to learn the best way to do this. Basically, I want to have a drop-down list with values ​​empty and 0 - 100.

What is the best way to do this without manually entering each one. I guess this is through some sort of list associated with a drop down list.

Thank you in advance for your help.

+4
source share
10 answers

Here is one way to do this:

ddl.Items.AddRange(Enumerable.Range(0, 100).Select (e => new ListItem(e.ToString())).ToArray()); 
+9
source

You can just use a for loop.

 myControl.Items.Add(new ListItem(string.Empty, -1)); for(int j = 0; j < 100; j++) { var newOption = new ListItem("Item #" + (j + 1).ToString(), j.ToString()); myControl.Items.Add(newOption); } 
+6
source

If you linked the list (array, collection, etc.) as a data source in the drop-down list (winforms? Webforms?), Elements will always be created. If you do not want to add each item manually, you can do this with code:

 // this code is for winforms dropDown.Items.Clear(); dropDown.Items.Add( string.Empty ); for(int i = 0; i <= 100; i++ ) { dropDown.Items.Add( i.ToString() ); } 
+3
source

For example, in asp.net MVC:

Controller:

 ViewData["list"] = new SelectList(Enumerable.Range(0, 101) .Select(p => new SelectListItem() { Text = p.ToString(), Value = p.ToString() })); 

View:

 <%=Html.DropDownList("numbers", ViewData["list"] as SelectList, "Select a number") %> 
+2
source

If these are web forms:
I assume you want something like this in your page_load event.

 if(Page.IsNotPostBack) { DropDownList1.Items.Add(new ListItem("","")); for(int i = 0; i <= 100; i++) DropDownList1.Items.Add(new ListItem(i.ToString(), i.ToString()); } 
+1
source
 ddl.DataSource = Enumerable.Range(1, 100); ddl.DataBind(); 
+1
source
 combo.Items.Add("") for (int i = 0; i < 100; i++) combo.Items.Add(i) 

Also consider using NumericUpDown with a maximum value of 100. This will not give you an empty choice, but a more convenient usability choice is possible.

0
source

Create a utility to generate your values:

 public class Utils { public static IEnumerable<string> GetSequenceEntries(long maxValue) { yield return string.Empty; for(int i=1; i<=maxValue; i++) { yield return i.ToString(); } } } 

Then, for the WinForms application, bind it the same way as this:

 private void Form1_Load(object sender, EventArgs e) { comboBox1.DataSource = Utilities.Utils.GetSequenceEntries(100).ToList<string>(); } 

Or for ASP.NET bind it like this:

 protected void Page_Load(object sender, EventArgs e) { ddl1.DataSource = Utilities.Utils.GetSequenceEntries(100); ddl1.DataBind(); } 
0
source

B. B:

 For i As Integer = 0 To 100 ddlperiod.Items.Add(i) Next 
0
source

Anyone can help me, I want to show a list of page load records in the Outlook grid in devexpress. Any, please let me know what request to show the list. grid name - outlookgrid1 table name - patent database - ABC

-1
source

All Articles