Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在数据绑定组合框顶部插入自定义值_C#_Winforms_Data Binding_Combobox - Fatal编程技术网

C# 在数据绑定组合框顶部插入自定义值

C# 在数据绑定组合框顶部插入自定义值,c#,winforms,data-binding,combobox,C#,Winforms,Data Binding,Combobox,我想在组合框顶部插入一个默认值。请告诉我这样做的正确方法 我尝试的 我的代码: using (var salaryslipEntities = new salary_slipEntities()) { Employee emp = new Employee(); cmbEmployeeName.DataSource = salaryslipEntities.Employees.ToLis

我想在组合框顶部插入一个默认值。请告诉我这样做的正确方法

我尝试的

我的代码:

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


设置DataSource属性时,无法修改Items集合。

您可以使用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";

您可以将emp添加到列表中,然后重新绑定数据。您可以告诉我类似的情况:var sourceEmp=salaryslipenties.Employees.ToList();cmbeployeename.DataSource=sourceEmp;cmbeployeename.DataBind();sourceEmp.Insert(0,新员工());cmbeployeename.DataSource=sourceEmp;cmbeployeename.DataBind();
public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}