Export (0) Print
Expand All

BindingSource Class

Encapsulates the data source for a form.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

[ComplexBindingPropertiesAttribute("DataSource", "DataMember")]
public class BindingSource : Component, 
	IBindingListView, IBindingList, IList, ICollection, IEnumerable, 
	ITypedList, ICancelAddNew, ISupportInitializeNotification, ISupportInitialize, ICurrencyManagerProvider

The BindingSource type exposes the following members.

  NameDescription
Public methodBindingSource()Initializes a new instance of the BindingSource class to the default property values.
Public methodBindingSource(IContainer)Initializes a new instance of the BindingSource class and adds the BindingSource to the specified container.
Public methodBindingSource(Object, String)Initializes a new instance of the BindingSource class with the specified data source and data member.
Top

  NameDescription
Public propertyAllowEditGets a value indicating whether items in the underlying list can be edited.
Public propertyAllowNewGets or sets a value indicating whether the AddNew method can be used to add items to the list.
Public propertyAllowRemoveGets a value indicating whether items can be removed from the underlying list.
Protected propertyCanRaiseEventsGets a value indicating whether the component can raise an event. (Inherited from Component.)
Public propertyContainerGets the IContainer that contains the Component. (Inherited from Component.)
Public propertyCountGets the total number of items in the underlying list, taking the current Filter value into consideration.
Public propertyCurrencyManagerGets the currency manager associated with this BindingSource.
Public propertyCurrentGets the current item in the list.
Public propertyDataMemberGets or sets the specific list in the data source to which the connector currently binds to.
Public propertyDataSourceGets or sets the data source that the connector binds to.
Protected propertyDesignModeGets a value that indicates whether the Component is currently in design mode. (Inherited from Component.)
Protected propertyEventsGets the list of event handlers that are attached to this Component. (Inherited from Component.)
Public propertyFilterGets or sets the expression used to filter which rows are viewed.
Public propertyIsBindingSuspendedGets a value indicating whether the list binding is suspended.
Public propertyIsFixedSizeGets a value indicating whether the underlying list has a fixed size.
Public propertyIsReadOnlyGets a value indicating whether the underlying list is read-only.
Public propertyIsSortedGets a value indicating whether the items in the underlying list are sorted.
Public propertyIsSynchronizedGets a value indicating whether access to the collection is synchronized (thread safe).
Public propertyItemGets or sets the list element at the specified index.
Public propertyListGets the list that the connector is bound to.
Public propertyPositionGets or sets the index of the current item in the underlying list.
Public propertyRaiseListChangedEventsGets or sets a value indicating whether ListChanged events should be raised.
Public propertySiteGets or sets the ISite of the Component. (Inherited from Component.)
Public propertySortGets or sets the column names used for sorting, and the sort order for viewing the rows in the data source.
Public propertySortDescriptionsGets the collection of sort descriptions applied to the data source.
Public propertySortDirectionGets the direction the items in the list are sorted.
Public propertySortPropertyInfrastructure. Gets the PropertyDescriptor that is being used for sorting the list.
Public propertySupportsAdvancedSortingGets a value indicating whether the data source supports multi-column sorting.
Public propertySupportsChangeNotificationGets a value indicating whether the data source supports change notification.
Public propertySupportsFilteringGets a value indicating whether the data source supports filtering.
Public propertySupportsSearchingGets a value indicating whether the data source supports searching with the Find method.
Public propertySupportsSortingGets a value indicating whether the data source supports sorting.
Public propertySyncRootGets an object that can be used to synchronize access to the underlying list.
Top

  NameDescription
Public methodAddAdds an existing item to the internal list.
Public methodAddNewAdds a new item to the underlying list.
Public methodApplySort(ListSortDescriptionCollection)Sorts the data source with the specified sort descriptions.
Public methodApplySort(PropertyDescriptor, ListSortDirection)Sorts the data source using the specified property descriptor and sort direction.
Public methodCancelEditCancels the current edit operation.
Public methodClearRemoves all elements from the list.
Public methodContainsDetermines whether an object is an item in the list.
Public methodCopyToCopies the contents of the List to the specified array, starting at the specified index value.
Public methodCreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public methodDispose()Releases all resources used by the Component. (Inherited from Component.)
Protected methodDispose(Boolean)Releases the unmanaged resources used by the BindingSource and optionally releases the managed resources. (Overrides Component.Dispose(Boolean).)
Public methodEndEditApplies pending changes to the underlying data source.
Public methodEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodFinalizeReleases unmanaged resources and performs other cleanup operations before the Component is reclaimed by garbage collection. (Inherited from Component.)
Public methodFind(PropertyDescriptor, Object)Searches for the index of the item that has the given property descriptor.
Public methodFind(String, Object)Returns the index of the item in the list with the specified property name and value.
Public methodGetEnumeratorRetrieves an enumerator for the List.
Public methodGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetItemPropertiesRetrieves an array of PropertyDescriptor objects representing the bindable properties of the data source list type.
Public methodGetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodGetListNameGets the name of the list supplying data for the binding.
Public methodGetRelatedCurrencyManagerGets the related currency manager for the specified data member.
Protected methodGetServiceReturns an object that represents a service provided by the Component or by its Container. (Inherited from Component.)
Public methodGetTypeGets the Type of the current instance. (Inherited from Object.)
Public methodIndexOfSearches for the specified object and returns the index of the first occurrence within the entire list.
Public methodInitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public methodInsertInserts an item into the list at the specified index.
Protected methodMemberwiseClone()Creates a shallow copy of the current Object. (Inherited from Object.)
Protected methodMemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public methodMoveFirstMoves to the first item in the list.
Public methodMoveLastMoves to the last item in the list.
Public methodMoveNextMoves to the next item in the list.
Public methodMovePreviousMoves to the previous item in the list.
Protected methodOnAddingNewRaises the AddingNew event.
Protected methodOnBindingCompleteRaises the BindingComplete event.
Protected methodOnCurrentChangedRaises the CurrentChanged event.
Protected methodOnCurrentItemChangedRaises the CurrentItemChanged event.
Protected methodOnDataErrorRaises the DataError event.
Protected methodOnDataMemberChangedRaises the DataMemberChanged event.
Protected methodOnDataSourceChangedRaises the DataSourceChanged event.
Protected methodOnListChangedRaises the ListChanged event.
Protected methodOnPositionChangedRaises the PositionChanged event.
Public methodRemoveRemoves the specified item from the list.
Public methodRemoveAtRemoves the item at the specified index in the list.
Public methodRemoveCurrentRemoves the current item from the list.
Public methodRemoveFilterRemoves the filter associated with the BindingSource.
Public methodRemoveSortRemoves the sort associated with the BindingSource.
Public methodResetAllowNewInfrastructure. Reinitializes the AllowNew property.
Public methodResetBindingsCauses a control bound to the BindingSource to reread all the items in the list and refresh their displayed values.
Public methodResetCurrentItemCauses a control bound to the BindingSource to reread the currently selected item and refresh its displayed value.
Public methodResetItemCauses a control bound to the BindingSource to reread the item at the specified index, and refresh its displayed value.
Public methodResumeBindingResumes data binding.
Public methodSuspendBindingSuspends data binding to prevent changes from updating the bound data source.
Public methodToStringReturns a String containing the name of the Component, if any. This method should not be overridden. (Inherited from Component.)
Top

  NameDescription
Public eventAddingNewOccurs before an item is added to the underlying list.
Public eventBindingCompleteOccurs when all the clients have been bound to this BindingSource.
Public eventCurrentChangedOccurs when the currently bound item changes.
Public eventCurrentItemChangedOccurs when a property value of the Current property has changed.
Public eventDataErrorOccurs when a currency-related exception is silently handled by the BindingSource.
Public eventDataMemberChangedOccurs when the DataMember property value has changed.
Public eventDataSourceChangedOccurs when the DataSource property value has changed.
Public eventDisposedOccurs when the component is disposed by a call to the Dispose method. (Inherited from Component.)
Public eventListChangedOccurs when the underlying list changes or an item in the list changes.
Public eventPositionChangedOccurs after the value of the Position property has changed.
Top

  NameDescription
Public Extension MethodAsParallel()Overloaded. Enables parallelization of a query. (Defined by ParallelEnumerable.)
Public Extension MethodAsParallel()Overloaded. (Defined by ParallelEnumerable.)
Public Extension MethodAsQueryable()Overloaded. Converts an IEnumerable to an IQueryable. (Defined by Queryable.)
Public Extension MethodAsQueryable()Overloaded. (Defined by Queryable.)
Public Extension MethodCast<TResult>()Overloaded. Casts the elements of an IEnumerable to the specified type. (Defined by Enumerable.)
Public Extension MethodCast<TResult>()Overloaded. (Defined by Enumerable.)
Public Extension MethodOfType<TResult>()Overloaded. Filters the elements of an IEnumerable based on a specified type. (Defined by Enumerable.)
Public Extension MethodOfType<TResult>()Overloaded. (Defined by Enumerable.)
Top

  NameDescription
Explicit interface implemetationPrivate methodIBindingList.AddIndexAdds the PropertyDescriptor to the indexes used for searching.
Explicit interface implemetationPrivate methodIBindingList.RemoveIndexRemoves the System.ComponentModel.PropertyDescriptor from the indexes used for searching.
Explicit interface implemetationPrivate methodICancelAddNew.CancelNewDiscards a pending new item from the collection.
Explicit interface implemetationPrivate methodICancelAddNew.EndNewCommits a pending new item to the collection.
Explicit interface implemetationPrivate methodISupportInitialize.BeginInitSignals the BindingSource that initialization is starting.
Explicit interface implemetationPrivate methodISupportInitialize.EndInitSignals the BindingSource that initialization is complete.
Explicit interface implemetationPrivate eventISupportInitializeNotification.InitializedOccurs when the BindingSource is initialized.
Explicit interface implemetationPrivate propertyISupportInitializeNotification.IsInitializedGets a value indicating whether the BindingSource is initialized.
Top

The BindingSource component serves many purposes. First, it simplifies binding controls on a form to data by providing currency management, change notification, and other services between Windows Forms controls and data sources. This is accomplished by attaching the BindingSource component to your data source using the DataSource property. For complex binding scenarios you can optionally set the DataMember property to a specific column or list in the data source. You then bind controls to the BindingSource. All further interaction with the data is accomplished with calls to the BindingSource component. For examples on how the BindingSource can simplify the binding process, see How to: Bind Windows Forms Controls to DBNull Database Values and How to: Handle Errors and Exceptions that Occur with Databinding. Navigation and updating of the data source is accomplished through methods such as MoveNext, MoveLast, and Remove. Operations such as sorting and filtering are handled through the Sort and Filter properties. For more information on using sorting and filtering with the BindingSource, see How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component.

In addition, the BindingSource component can act as a strongly typed data source. Typically the type of the underlying data source is fixed through one of the following mechanisms:

  • Use the Add method to add an item to the BindingSource component.

  • Set the DataSource property to a list, single object, or type.

Both of these mechanisms create a strongly-typed list. For more information on how to use the BindingSource to bind to a type, see How to: Bind a Windows Forms Control to a Type. You can also use the BindingSource to bind your controls to a factory object. For more information on how to do this, see How to: Bind a Windows Forms Control to a Factory Object.

NoteNote

Because a BindingSource handles both simple and complex data sources, terminology is problematic. Within this class documentation, the term list refers to a data collection within the hosted data source, and item denotes a single element. When discussing functionality associated with complex data sources, the equivalent terms table and row are used.

BindingSource provides members for accessing the underlying data. The current item can be retrieved through the Current property, and the entire list can be retrieved through the List property. Editing operations are supported on the current item through Current and the RemoveCurrent, EndEdit, CancelEdit and Add and AddNew methods. Although currency management is handled automatically for all underlying data source types, this class exposes a number of events, such as CurrentItemChanged and DataSourceChanged, that allow for customization.

Data sources that are bound to a BindingSource component can also be navigated and managed with the BindingNavigator class, which provides a VCR-like user interface (UI) for navigating items within a list. Although BindingNavigator can be bound to any data source, it was designed to integrate with a BindingSource component through its BindingNavigator.BindingSource property.

The default property for the BindingSource class is DataSource. The default event is CurrentChanged.

Caution noteCaution

  Many of the members of the BindingSource class operate on the underlying list represented by the List property and simply refer their operation to the underlying list. Therefore, when the BindingSource is bound to a custom implementation of IList, the exact behavior of these members may differ from the behavior described in the class documentation. For example, the RemoveAt method calls IList.RemoveAt. The BindingSource documentation describes the RemoveAt method with the understanding that the RemoveAt method for the underlying IList is correctly implemented.

The following code example demonstrates a ListBox bound to a BindingSource. The BindingSource is bound to a BindingList<T> that contains a list of fonts.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BindingSourceExamples
{
    public class Form1 : Form
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }

        public Form1()
        {
            this.Load += new EventHandler(Form1_Load);
        }

        private TextBox textBox1;
        private Button button1;
        private ListBox listBox1;

        private BindingSource binding1;
        void Form1_Load(object sender, EventArgs e)
        {
            listBox1 = new ListBox();
            textBox1 = new TextBox();
            binding1 = new BindingSource();
            button1 = new Button();
            listBox1.Location = new Point(140, 25);
            listBox1.Size = new Size(123, 160);
            textBox1.Location = new Point(23, 70);
            textBox1.Size = new Size(100, 20);
            textBox1.Text = "Wingdings";
            button1.Location = new Point(23, 25);
            button1.Size = new Size(75, 23);
            button1.Text = "Search";
            button1.Click += new EventHandler(this.button1_Click);
            this.ClientSize = new Size(292, 266);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.listBox1);

            MyFontList fonts = new MyFontList();
            for (int i = 0; i < FontFamily.Families.Length; i++)
            {
                if (FontFamily.Families[i].IsStyleAvailable(FontStyle.Regular))
                    fonts.Add(new Font(FontFamily.Families[i], 11.0F, FontStyle.Regular));
            }
            binding1.DataSource = fonts;
            listBox1.DataSource = binding1;
            listBox1.DisplayMember = "Name";

        }


        private void button1_Click(object sender, EventArgs e)
        {
            if (binding1.SupportsSearching != true)
                MessageBox.Show("Cannot search the list.");
            else
            {
                int foundIndex = binding1.Find("Name", textBox1.Text);
                if (foundIndex > -1)
                    listBox1.SelectedIndex = foundIndex;
                else
                    MessageBox.Show("Font was not found.");
            }
        }
    }

    public class MyFontList : BindingList<Font>
    {

        protected override bool SupportsSearchingCore
        {
            get { return true; }
        }
        protected override int FindCore(PropertyDescriptor prop, object key)
        {
            // Ignore the prop value and search by family name. 
            for (int i = 0; i < Count; ++i)
            {
                if (Items[i].FontFamily.Name.ToLower() == ((string)key).ToLower())
                    return i;

            }
            return -1;
        }


    }

}

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft