Problem Scenario
The Windows Forms ComboBox
control is used to display data in a drop-down combo box. When the data source property of the combo box is binded with data, then you will not be able to add any item through the Items.Add()
function.
So, let's go through a demo by the help of which you can understand the problem scenario and its solution. Suppose we have a class named Person
and we will create an IList
to store this Person
list.
Person p = null;
IList list = new ArrayList();
p = new Person();
p.PersonID = 1;
p.PersonName = "Ali";
list.Add(p);
p = new Person();
p.PersonID = 2;
p.PersonName = "Raza";
list.Add(p);
p = new Person();
p.PersonID = 3;
p.PersonName = "Shaikh";
list.Add(p);
We have added three persons information in the list, now we want to bind the combo box with this data.
this.comboBox1.DataSource = list;
this.comboBox1.DisplayMember = "PersonName";
this.comboBox1.ValueMember = "PersonID";
Now, the data is binded with the Combo Box, and we will see the following kind of look on the interface.
Now, what's the problem here? In most of the professional applications, there is a select option at the top of each combo box, so that the user can choose an option if he desires, or else he can leave the combo box without selecting anything. So, as a common practice, one will write this line of code:
this.comboBox1.Items.Add("< Select Person >");
this.comboBox1.Items.Insert(0, "< Select Person >");
Which ends up giving this error:
Solution
This thing can be achieved by using the following two classes of System.Reflection
:
Activator
: Contains methods to create types of objects locally or remotely, or obtain references to existing remote objectsPropertyInfo
: Discovers the attributes of a property and provides access to property metadata.
Now, simply call this function to add the required item on the list.
private void AddItem(IList list, Type type, string valueMember,
string displayMember, string displayText)
{
Object obj = Activator.CreateInstance(type);
PropertyInfo displayProperty = type.GetProperty(displayMember);
displayProperty.SetValue(obj, displayText, null);
PropertyInfo valueProperty = type.GetProperty(valueMember);
valueProperty.SetValue(obj, -1, null);
list.Insert(0, obj);
}
Then, add the following line of code just before the data binding with the combo box:
AddItem(list, typeof(Person), "PersonID", "PersonName", "< Select Option >");
In the end, the interface looks like this, looking like a professional effort to deal with the data inside the combo box.
History
- 7th October, 2006: Initial post