Reputation: 43
How to add multiple items to a combobox using single line of code?
public Form1()
{
InitializeComponent();
comboBox1.Items.Add("simple");
comboBox1.Items.Add("continuous");
comboBox1.Items.Add("perfect");
comboBox1.Items.Add("perfect continuous");
}
Upvotes: 3
Views: 17691
Reputation: 1
Another way to solve this problem is in the [Design] tab. You just have to select you comboBox and open the proprierties, go to "Data" then to "Items" and just put this "(Collection)". Now you access the new part and put all the items you desire.
Upvotes: -1
Reputation: 9991
"How to add multiple items to a combobox using single line of code?"
If you look at the documentation for ComboBox.ObjectCollection you'll see that there's a method named AddRange. MSDN describes this method as:
Adds an array of items to the list of items for a ComboBox.
So the one-liner you're looking for is:
c#:
comboBox1.Items.AddRange(new string[] { "simple", "continuous", "perfect", "perfect continuous" });
vb.net:
ComboBox1.Items.AddRange(New String() {"simple", "continuous", "perfect", "perfect continuous"})
Upvotes: 9
Reputation: 7181
There is no reason to do what you're asking. Reducing lines of code (LOC) unnecessarily is poor programming practice and should be avoided. Only do this where it makes sense and improves readability/understanding of the code.
When you're using a language that is compiled (and C# is compiled into an intermediate language) there really is no reason to care about how small you can make your source files, unless of course it's an improvement. When you're dealing with a scripting language where size may matter (like JavaScript for client-side code) minifiers or uglifiers take advantage of shortcuts to reduce as much whitespace as possible to reduce file sizes to speed downloads - but that's only necessary for released code - in development you keep it clean and readable.
Now, all that being said you can "shorten" your code by using an array of string
s and a foreach
loop.
public Form1 {
InitializeComponent();
string[] items = new string[] { "simple", "continuous", "perfect", "perfect continuous" };
foreach (string item in items) {
comboBox1.Items.Add(item);
}
}
Not quite as "one line" as you may want, but @OrelEraki proposed a one line solution that uses List
object created in a similar fashion to the string array seen here. What you see may not be "shorter" than your example but it doesn't grow significantly with more items like what you have will do.
Upvotes: 1