user3859356
user3859356

Reputation: 739

Insert Custom value at top of Databound ComboBOX

I want to insert a default value at top of my comboBox. Please Tell me a proper way to do so.

What I tried

my Code:

 using (var salaryslipEntities = new salary_slipEntities())
            {
                    Employee emp = new Employee();
                      cmbEmployeeName.DataSource = salaryslipEntities.Employees.ToList();
                         cmbEmployeeName.Items.Insert(0, "Select Employee");
                          }

error

Items collection cannot be modified when the DataSource property is set.

Upvotes: 0

Views: 119

Answers (1)

Seminda
Seminda

Reputation: 1773

You can do this using System.Reflection. check the code sample below.

write a common method to add a default item.

 private void AddItem(IList list, Type type, string valueMember,string displayMember, string displayText)
    {
        //Creates an instance of the specified type 
        //using the constructor that best matches the specified parameters.
        Object obj = Activator.CreateInstance(type);

        // Gets the Display Property Information
        PropertyInfo displayProperty = type.GetProperty(displayMember);

        // Sets the required text into the display property
        displayProperty.SetValue(obj, displayText, null);

        // Gets the Value Property Information
        PropertyInfo valueProperty = type.GetProperty(valueMember);

        // Sets the required value into the value property
        valueProperty.SetValue(obj, -1, null);

        // Insert the new object on the list
        list.Insert(0, obj);
    }

Then use that method like this.

List<Test> tests = new List<Test>();
        tests.Add(new Test { Id = 1, Name = "Name 1" });
        tests.Add(new Test { Id = 2, Name = "Name 2" });
        tests.Add(new Test { Id = 3, Name = "Name 3" });
        tests.Add(new Test { Id = 4, Name = "Name 4" });

        AddItem(tests, typeof(Test), "Id", "Name", "< Select Option >");
        comboBox1.DataSource = tests;
        comboBox1.ValueMember = "Id";
        comboBox1.DisplayMember = "Name";

I used this test class in the code

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Upvotes: 1

Related Questions