How to add items of array to combobox using c#?
This sample code is developed to add items of array to combobox. Code is in C# whereas application is windows based.
Properties of combobox can be set by using this code snippet which demonstrates the AddRange method.
Description -
AddRange method is used to add the elements of the specified collections to control.
using System;
using System.Collections.Generic;
public class Sample_For_Adding_items
{
public static void Main()
{
ArrayList sampleArray = new ArrayList();
sampleArray.Add("India");
sampleArray.Add("China");
sampleArray.Add("USA");
sampleArray.Add("UK");
sampleArray.Add("Japan");
comboBox1.Items.AddRange(sampleArray);
}
}
Another way is -
You can set ItemsSource property of combobox to sampleArray.
comboBox1.ItemsSource = sampleArray;
or
comboBox1.Items.AddRange(new[] { "India", "China", "USA", "UK" , "Japan" });
If the range is null then it will throw ArgumentNullException.
Scenario where to use Add and where to use Addrange -
If user wants to add individual element in the arraylist, that time Add method is used.
If user wants to add a specific range of elements then AddRange is used.
You can use below code snippet for adding Item in C-Sharp and XML
Code Behind for adding item in C#:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
comboBox1.Items.Add("Prem");
comboBox1.Items.Add("Kumar");
comboBox1.Items.Add("Mahto");
}
http://msdn.microsoft.com/en-us/library/aa983551%28v=vs.71%29.aspx