【问题标题】:Set SelectedItem on a combobox bound to datasource在绑定到数据源的组合框上设置 SelectedItem
【发布时间】:2012-04-18 10:41:52
【问题描述】:
List<Customer> _customers = getCustomers().ToList();
BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = _customers;
comboBox.DataSource = bsCustomers.DataSource;
comboBox.DisplayMember = "name";
comboBox.ValueMember = "id";

现在如何将组合框的项目设置为列表中第一个以外的其他内容? 试过了 comboBox.SelectedItem = someCustomer; ...还有很多其他的东西,但到目前为止还没有运气...

【问题讨论】:

    标签: c# combobox datasource selecteditem


    【解决方案1】:

    你应该这样做

    comboBox.SelectedValue = "valueToSelect";
    

    comboBox.SelectedIndex = n;
    

    comboBox.Items[n].Selected = true;
    

    【讨论】:

    • comboBox.Items[n].Selected = true;对我不起作用(可能是 CF 问题),但 SelectedValue 可以,我之前尝试过,但值错误。谢谢。
    • 我想指出,要让它工作,我必须指定作为值成员的字段,而不仅仅是对象。所以对于上面的客户,我不得不使用comboBox.SelectedValue = customerToSelect.id
    【解决方案2】:

    您的绑定代码不完整。试试这个:

    BindingSource bsCustomers = new BindingSource();
    bsCustomers.DataSource = _customers;
    
    comboBox.DataBindings.Add(
        new System.Windows.Forms.Binding("SelectedValue", bsCustomers, "id", true));
    comboBox.DataSource = bsCustomers;
    comboBox.DisplayMember = "name";
    comboBox.ValueMember = "id";
    

    在大多数情况下,您可以在设计器中完成此任务,而不是在代码中完成。

    首先在 Visual Studio 的“数据源”窗口中添加数据源。从菜单查看>其他窗口>数据源打开它。添加Customer 类型的Object 数据源。在数据源中,您将看到客户的属性。通过右键单击属性,您可以更改与其关联的默认控件。

    现在您可以简单地将属性从“数据源”窗口拖到您的表单中。当您放下第一个控件时,Visual Studio 会自动将 A BindingSourceBindingNavigator 组件添加到您的表单中。 BindingNavigator 是可选的,如果您不需要它,您可以安全地删除它。 Visual Studio 也完成了所有的连接。您可以通过属性窗口对其进行调整。有时这对于组合框是必需的。

    在您的代码中只剩下一件事要做:将实际数据源分配给绑定源:

    customerBindingSource.DataSource = _customers;
    

    【讨论】:

    • 这样它就会在 comboBox.ValueMember = "id";出于某种原因?
    • 我建议您将BindingSource 作为组件添加到设计器中的表单中(参见ToolboxData 部分)。然后您可以通过属性窗口设置所有这些属性。如果您首先在 VS 的Data Sources 窗口中定义一个对象数据源,那就更容易了。然后,您可以简单地将字段从该窗口拖到您的表单中,绑定线自动完成。如果您这样做,则会自动插入 BindingSourceBindingNavigator。然后,如果您不需要 BindingNavigator,您可以安全地删除它。
    • 哪个属性或对象代表绑定的选中项?不是 bsCustomers 一个列表,它有多个“id”
    • 数据源是 List&lt;Customer&gt;Customer 具有 idname 属性。 Customer.id 绑定到 ComboBox.SelectedValue 属性。
    【解决方案3】:

    这对我有用

    bsCustomers.Position = comboBox.Items.IndexOf(targetCustomer);
    

    【讨论】:

      猜你喜欢
      • 2011-06-28
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多