【问题标题】:Insert Custom value at top of Databound ComboBOX在 Databound ComboBOX 顶部插入自定义值
【发布时间】:2014-09-23 05:47:05
【问题描述】:

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

我尝试了什么

我的代码:

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

错误

设置 DataSource 属性时无法修改项目集合。

【问题讨论】:

  • 您可以将emp添加到您的列表中并重新绑定数据
  • 你能告诉我怎么做吗
  • 类似的东西:
  • var sourceEmp =salaryslipEntities.Employees.ToList(); cmbEmployeeName.DataSource = sourceEmp; cmbEmployeeName.DataBind(); sourceEmp.Insert(0, new Employee()); cmbEmployeeName.DataSource = sourceEmp; cmbEmployeeName.DataBind();

标签: c# winforms data-binding combobox


【解决方案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; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2012-03-07
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2013-09-26
    相关资源
    最近更新 更多