【问题标题】:how to bind a combobox automatically when Customer is entered in CustomerEntry form在 CustomerEntry 表单中输入客户时如何自动绑定组合框
【发布时间】:2011-04-06 07:08:45
【问题描述】:

在我的项目中,我有两种表单 BillEntry 和 CustomerEntry。

在 CustomerEntry 中添加了新客户。

当按下新按钮时,我正在打开一个新的 CustomerEntry 表单,这里的 BillEntry 表单已经在 CustomerEntry 表单的后面打开。我不希望我的 BillEntry 表单关闭..

这里的客户组合框不会接受在 customerentry 中输入的新客户..

我正在将 BillEntry 表单的构造函数中的客户组合框与 LINQ 绑定...

并且在组合框输入事件上绑定组合框也不起作用..

请告诉我该怎么做...

linq 查询还是代码没有问题。 问题是我在哪里可以调用绑定组合框的绑定方法?

public BillEntry()
{
      InitializeComponent();
      Customer_Binding();           
}

private void Customer_Binding()
{
      DataClasses1DataContext db = new DataClasses1DataContext();
      cbx_customer.DisplayMember = "CustomerName";
      cbx_customer.ValueMember = "CustomerID";
      cbx_customer.DataSource = db.Customers;
}

【问题讨论】:

  • 能否请您向我们展示您的 LINQ 查询返回的内容,以及您目前如何将其绑定到组合框?

标签: c# winforms binding


【解决方案1】:

使用 BindingSources 可能会更好。

将 BindingSource 添加到您的表单,然后在组合框的属性中将 DataSource 属性设置为您刚刚添加的 bindingSource。

comboBox1.DataSource = bindingSource1;

然后您将 Bi​​ndingSource 的数据源设置为您的客户列表:

例如像

bindingSource1.DataSource = customers;

//you still need to tell the combo box what to show
comboBox1.DisplayMember = "SomeText"; 
comboBox1.ValueMember = "SomeValue";

然后,当您向客户列表添加新数据时,只需调用:

bindingSource1.ResetBindings(false);

【讨论】:

    【解决方案2】:

    绑定到字符串时,通常很简单:

    List<string> items = new List<string> { "One", "Two", "Three" };
    comboBox1.DataSource = items;
    

    但如果您使用的是对象,则可能会有点棘手:

    给定一个对象,“TestObject”

    public class TestObject
    {
        public string SomeText { get; set; }
        public int SomeValue { get; set; }
    }
    

    你像这样绑定它:

    comboBox1.DataSource = new List<TestObject> 
    { 
        new TestObject { SomeText = "One", SomeValue = 1 },
        new TestObject { SomeText = "Two", SomeValue = 2 },
        new TestObject { SomeText = "Three", SomeValue = 3 }
    };
    comboBox1.DisplayMember = "SomeText";
    comboBox1.ValueMember = "SomeValue";
    

    “DisplayMember”和“ValueMember”是您希望分别显示和用作值的对象的属性名称

    【讨论】:

    • 我已经知道绑定...我想在添加客户时自动重新绑定...
    • BindingSources 可能是一个更好的选择。请参阅我的第二个答案。
    猜你喜欢
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多