2014-09-23 38 views
0

我想在我的comboBox顶部插入默认值。请告诉我一个正确的方法来做到这一点。在Databound顶部插入自定义值ComboBOX

我试过

我的代码:

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

错误,当DataSource属性设置

Items集合不能被修改。

+0

您可以添加EMP到您的列表并重新绑定数据 – Jurion 2014-09-23 05:48:50

+0

u能请告诉如何 – user3859356 2014-09-23 05:54:53

+0

类似的东西: – Jurion 2014-09-23 05:59:16

回答

1

你可以使用System.Reflection来做到这一点。检查下面的代码示例。

编写一个通用方法来添加默认项目。

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); 
    } 

然后使用这样的方法。

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"; 

我用这个测试类中的代码

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