Reputation: 137
Is there a shorter way to add all the numbers from 1-100 into a combobox in c#? Currently the method i am aware of is to add 1 by 1 manually and that consumes time. Is there a faster way to do it?
P.S I am very new to c#, so if you could kindly explain your code to me that would be very helpful. :D
Upvotes: 1
Views: 3284
Reputation: 368
This question has already been answered by Alfie Goodacre and is an efficient way to add multiple items to a combobox with little code, but for people new to c# or programming in general, the simplest way to add numerous numbers to a combobox would be a single for loop as follows, wouldn't it?
for (int i = 1; i <= 100; i++)
{
comboBox1.Items.Add(i);
}
The integer variable "i" starts at 1 and increments by one. As long as it's lower or equal to 100, its value will be added as an item to the combobox.
Upvotes: 3
Reputation: 2793
Firstly you should create an array containing 1-100. This can be done like so
int[] list = Enumerable.Range(1, 100).Cast<object>().ToArray();
After this you need to add them all at once with AddRange()
comboBox1.Items.AddRange(list);
This code will add 1-100 to your comboBox
To use this code you need using System.Linq;
at the top of your document
EDIT: Thanks to @Badiparmagi for correcting me on adding the values to the comboBox
Upvotes: 8