如何:将 Windows 窗体 ComboBox 控件或 ListBox 控件绑定到数据How to: Bind a Windows Forms ComboBox or ListBox Control to Data

可以将绑定ComboBoxListBox到数据以执行任务,例如浏览数据库中的数据,输入新数据,或编辑现有数据。You can bind the ComboBox and ListBox to data to perform tasks such as browsing data in a database, entering new data, or editing existing data.

若要将 ComboBox 或 ListBox 控件绑定To bind a ComboBox or ListBox control

  1. 设置DataSource到数据源对象的属性。Set the DataSource property to a data source object. 可能的数据源包括BindingSource绑定到数据、 数据表、 数据视图、 数据集,数据视图,管理器、 一个数组或实现任何类IList接口。Possible data sources include a BindingSource bound to data, a data table, a data view, a dataset, a data view manager, an array, or any class that implements the IList interface. 有关详细信息,请参阅支持的 Windows 窗体数据源For more information, see Data Sources Supported by Windows Forms.

  2. 如果要绑定到一个表,设置DisplayMember属性设置为数据源中的列的名称。If you are binding to a table, set the DisplayMember property to the name of a column in the data source.

    - 或 -- or -

    如果要绑定到IList,将显示成员设置为列表中的类型的公共属性。If you are binding to an IList, set the display member to a public property of the type in the list.

    Private Sub BindComboBox()  
      ComboBox1.DataSource = DataSet1.Tables("Suppliers")  
      ComboBox1.DisplayMember = "ProductName"  
    End Sub  
    
    private void BindComboBox()  
    {  
      comboBox1.DataSource = dataSet1.Tables["Suppliers"];  
      comboBox1.DisplayMember = "ProductName";  
    }  
    

    备注

    如果绑定到数据源不实现IBindingList接口,如ArrayList,更新数据源时,将不会更新绑定的控件的数据。If you are bound to a data source that does not implement the IBindingList interface, such as an ArrayList, the bound control's data will not be updated when the data source is updated. 例如,如果您有一个组合框绑定到ArrayList并将数据添加到ArrayList,这些新项将不会显示在组合框中。For example, if you have a combo box bound to an ArrayList and data is added to the ArrayList, these new items will not appear in the combo box. 但是,可以强制组合框,以通过调用更新SuspendBindingResumeBinding的实例上的方法BindingContext控件所绑定到类。However, you can force the combo box to be updated by calling the SuspendBinding and ResumeBinding methods on the instance of the BindingContext class to which the control is bound.

请参阅See also