共用方式為


BindingSource 類別

定義

封裝窗體的數據源。

public ref class BindingSource : System::ComponentModel::Component, System::Collections::IList, System::ComponentModel::IBindingListView, System::ComponentModel::ICancelAddNew, System::ComponentModel::ISupportInitializeNotification, System::ComponentModel::ITypedList, System::Windows::Forms::ICurrencyManagerProvider
public ref class BindingSource : System::ComponentModel::Component, System::Collections::IList, System::ComponentModel::IBindingListView, System::ComponentModel::ICancelAddNew, System::ComponentModel::ISupportInitialize, System::ComponentModel::ISupportInitializeNotification, System::ComponentModel::ITypedList, System::Windows::Forms::ICurrencyManagerProvider
[System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")]
public class BindingSource : System.ComponentModel.Component, System.Collections.IList, System.ComponentModel.IBindingListView, System.ComponentModel.ICancelAddNew, System.ComponentModel.ISupportInitializeNotification, System.ComponentModel.ITypedList, System.Windows.Forms.ICurrencyManagerProvider
[System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")]
public class BindingSource : System.ComponentModel.Component, System.Collections.IList, System.ComponentModel.IBindingListView, System.ComponentModel.ICancelAddNew, System.ComponentModel.ISupportInitialize, System.ComponentModel.ISupportInitializeNotification, System.ComponentModel.ITypedList, System.Windows.Forms.ICurrencyManagerProvider
[<System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")>]
type BindingSource = class
    inherit Component
    interface IBindingListView
    interface IBindingList
    interface IList
    interface ICollection
    interface IEnumerable
    interface ITypedList
    interface ICancelAddNew
    interface ISupportInitializeNotification
    interface ISupportInitialize
    interface ICurrencyManagerProvider
[<System.ComponentModel.ComplexBindingProperties("DataSource", "DataMember")>]
type BindingSource = class
    inherit Component
    interface IBindingListView
    interface ICollection
    interface IEnumerable
    interface IList
    interface IBindingList
    interface ITypedList
    interface ICancelAddNew
    interface ISupportInitializeNotification
    interface ISupportInitialize
    interface ICurrencyManagerProvider
Public Class BindingSource
Inherits Component
Implements IBindingListView, ICancelAddNew, ICurrencyManagerProvider, IList, ISupportInitializeNotification, ITypedList
Public Class BindingSource
Inherits Component
Implements IBindingListView, ICancelAddNew, ICurrencyManagerProvider, IList, ISupportInitialize, ISupportInitializeNotification, ITypedList
繼承
屬性
實作

範例

以下程式碼範例展示了 ListBoxBindingSource的束縛。 綁 BindingSource 定在包含字型列表的 上 BindingList<T>

using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace BindingSourceExamples;

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

    public Form1() => Load += Form1_Load;

    TextBox textBox1;
    Button button1;
    ListBox listBox1;

    BindingSource binding1;
    void Form1_Load(object sender, EventArgs e)
    {
        listBox1 = new ListBox();
        textBox1 = new TextBox();
        binding1 = [];
        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 += button1_Click;
        ClientSize = new Size(292, 266);
        Controls.Add(button1);
        Controls.Add(textBox1);
        Controls.Add(listBox1);

        MyFontList fonts = [];
        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";
    }

    void button1_Click(object sender, EventArgs e)
    {
        if (!binding1.SupportsSearching)
        {
            _ = 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 => 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.Equals((string)key, StringComparison.CurrentCultureIgnoreCase))
            {
                return i;
            }
        }
        return -1;
    }
}
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Public Class Form1
    Inherits Form

    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New Form1())

    End Sub

    Public Sub New()

    End Sub

    Private textBox1 As TextBox
    Private WithEvents button1 As Button
    Private listBox1 As ListBox
    Private components As IContainer
    Private binding1 As BindingSource

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        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"
        Me.ClientSize = New Size(292, 266)
        Me.Controls.Add(Me.button1)
        Me.Controls.Add(Me.textBox1)
        Me.Controls.Add(Me.listBox1)

        Dim fonts As New MyFontList()
        Dim i As Integer
        For i = 0 To FontFamily.Families.Length - 1
            If FontFamily.Families(i).IsStyleAvailable(FontStyle.Regular) Then
                fonts.Add(New Font(FontFamily.Families(i), 11.0F, FontStyle.Regular))
            End If
        Next i
        binding1.DataSource = fonts
        listBox1.DataSource = binding1
        listBox1.DisplayMember = "Name"

    End Sub
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles button1.Click

        If binding1.SupportsSearching <> True Then
            MessageBox.Show("Cannot search the list.")
        Else
            Dim foundIndex As Integer = binding1.Find("Name", textBox1.Text)
            If foundIndex > -1 Then
                listBox1.SelectedIndex = foundIndex
            Else
                MessageBox.Show("Font was not found.")
            End If
        End If

    End Sub
End Class

Public Class MyFontList
    Inherits BindingList(Of Font)

    Protected Overrides ReadOnly Property SupportsSearchingCore() As Boolean
        Get
            Return True
        End Get
    End Property
    
    Protected Overrides Function FindCore(ByVal prop As PropertyDescriptor, _
        ByVal key As Object) As Integer
        ' Ignore the prop value and search by family name.
        Dim i As Integer
        While i < Count
            If Items(i).FontFamily.Name.ToLower() = CStr(key).ToLower() Then
                Return i
            End If
            i += 1
        End While

        Return -1
    End Function
End Class

備註

這個 BindingSource 元件有許多用途。 首先,它透過提供 Windows 表單控制項與資料來源之間的貨幣管理、變更通知及其他服務,簡化了表單控制項與資料的綁定。 這是透過將元件附加 BindingSource 到你的資料來源上,並利用屬性 DataSource 來達成的。 對於複雜的綁定情境,你可以選擇性地將屬性設定 DataMember 為資料來源中的特定欄位或清單。 接著你將控制項綁定到 BindingSource. 所有後續與資料的互動皆透過呼叫 BindingSource 元件完成。 關於如何 BindingSource 簡化綁定流程的範例,請參考《 如何:將 Windows 表單控制項綁定到 DBNull 資料庫值 》以及 《如何處理 Databinding 發生的錯誤與異常》。 資料來源的導航與更新可透過 、 、 MoveLastRemove等方法MoveNext完成。 排序與篩選等操作則透過 Sort and Filter 屬性處理。 如需更多關於如何搭配 、 進行排序與篩選 BindingSource的資訊,請參閱 How to: Sort and Filter ADO.NET Data with the Windows Forms BindingSource Component

此外,該 BindingSource 元件可作為強型別資料來源。 通常底層資料來源的類型會透過以下機制之一來確定:

這兩種機制都會產生強型別的清單。 欲了解更多如何使用 BindingSource to 綁定到型別的資訊,請參見 How to: Bind a Windows Forms Control to a Type。 你也可以用 把 BindingSource 控制器綁定到工廠物件。 欲了解更多相關資訊,請參閱 「如何:將 Windows 表單控制項綁定到工廠物件」。

備註

由於 a BindingSource 同時處理簡單與複雜的資料來源,術語使用上存在問題。 在此類別文件中, 術語列表 指的是託管資料來源中的資料集合, 項目 則代表單一元素。 在討論複雜資料來源相關功能時,會使用等效的術語為 「table 」和 「row 」。

BindingSource 提供成員以存取底層資料。 目前的項目可以透過屬性 Current 檢索,整個清單也能透過屬性 List 檢索。 透過 、 EndEdit、 和 AddNewAddCancelEdit 方法,支援對當前項目CurrentRemoveCurrent的編輯操作。 雖然貨幣管理會自動處理所有底層資料來源類型,但此類別會暴露許多事件,如 CurrentItemChangedDataSourceChanged,允許自訂。

綁定到 BindingSource 元件的資料來源也可以用類別 BindingNavigator 來導航和管理,該類別提供類似 VCR 的使用者介面(UI),方便在清單中瀏覽項目。 雖然BindingNavigator可以綁定到任何資料來源,但它的設計目的是透過其BindingNavigator.BindingSource屬性與BindingSource元件整合。

BindingSource 類別的預設性質為 DataSource。 預設事件為 CurrentChanged

謹慎

該類別的許多成員 BindingSource 會根據該 List 屬性所代表的底層清單操作,並直接將其操作指向底層清單。 因此,當 綁 BindingSource 定於 的 IList自訂實作時,這些成員的具體行為可能與類別文件中描述的不同。 例如,該 RemoveAt 方法呼叫 IList.RemoveAt。 文件 BindingSource 描述 RemoveAt 方法時,理解 RemoveAt 該底層 IList 方法已正確實作。

建構函式

名稱 Description
BindingSource()

將該類別的新實例 BindingSource 初始化為預設屬性值。

BindingSource(IContainer)

初始化該類別的新實例 BindingSource ,並將 加入 BindingSource 指定的容器。

BindingSource(Object, String)

初始化一個新的類別實例 BindingSource ,包含指定的資料來源與資料成員。

屬性

名稱 Description
AllowEdit

會取得一個值,表示底層清單中的項目是否可以被編輯。

AllowNew

取得或設定一個值,指示該方法是否 AddNew() 可用來將項目加入清單。

AllowRemove

會取得一個值,表示項目是否可以從底層清單中移除。

CanRaiseEvents

取得值,指出元件是否可以引發事件。

(繼承來源 Component)
Container

得到 IContainer 包含 Component的 。

(繼承來源 Component)
Count

取得底層清單中項目的總數,並考慮當前 Filter 值。

CurrencyManager

會讓貨幣管理器與此 BindingSource相關聯。

Current

取得清單中目前的項目。

DataMember

取得或設定連接器目前綁定的資料來源中的特定清單。

DataSource

取得或設定連接器綁定的資料來源。

DesignMode

會得到一個值,表示目前 Component 是否處於設計模式。

(繼承來源 Component)
Events

會取得與此 Component連結的事件處理程序清單。

(繼承來源 Component)
Filter

取得或設定用來篩選顯示列的表達式。

IsBindingSuspended

會得到一個值,表示列表綁定是否被暫停。

IsFixedSize

會得到一個值,表示底層清單是否有固定大小。

IsReadOnly

會獲得一個值,表示底層清單是否為唯讀。

IsSorted

會取得一個值,表示底層清單中的項目是否已排序。

IsSynchronized

取得值,指出集合的存取是否同步處理 (線程安全)。

Item[Int32]

取得或設定清單元素在指定的索引位置。

List

會取得連接器綁定的清單。

Position

取得或設定底層清單中當前項目的索引。

RaiseListChangedEvents

取得或設定一個值,指示事件是否 ListChanged 應該被觸發。

Site

取得或設定 ISiteComponent

(繼承來源 Component)
Sort

取得或設定用於排序的欄位名稱,以及查看資料來源列的排序順序。

SortDescriptions

會把各種描述的集合套用到資料來源上。

SortDirection

它會取得清單中項目排序的方向。

SortProperty

取得 PropertyDescriptor 用於排序清單的資訊。

SupportsAdvancedSorting

會取得一個值,表示資料來源是否支援多欄排序。

SupportsChangeNotification

會獲得一個值,表示資料來源是否支援變更通知。

SupportsFiltering

會獲得一個值,表示資料來源是否支援過濾。

SupportsSearching

會得到一個值,表示資料來源是否支援使用該 Find(PropertyDescriptor, Object) 方法進行搜尋。

SupportsSorting

會取得一個值,表示資料來源是否支援排序。

SyncRoot

取得一個物件,可用來同步存取底層清單。

方法

名稱 Description
Add(Object)

將現有項目加入內部清單。

AddNew()

新增一個項目到底層清單中。

ApplySort(ListSortDescriptionCollection)

以指定的排序描述排序資料來源。

ApplySort(PropertyDescriptor, ListSortDirection)

利用指定的屬性描述符與排序方向來排序資料來源。

CancelEdit()

取消目前的編輯操作。

Clear()

從列表中移除所有元素。

Contains(Object)

判斷物件是否屬於清單中的項目。

CopyTo(Array, Int32)

將 的內容複製 List 到指定的陣列,從指定的索引值開始。

CreateObjRef(Type)

建立一個物件,包含產生代理伺服器所需的所有相關資訊,用於與遠端物件通訊。

(繼承來源 MarshalByRefObject)
Dispose()

釋放所有由 Component.

(繼承來源 Component)
Dispose(Boolean)

釋放 未管理的資源, BindingSource 並可選擇性地釋放受管理資源。

EndEdit()

將待處理變更套用到底層資料來源。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
Find(PropertyDescriptor, Object)

搜尋具有該屬性描述符的項目索引。

Find(String, Object)

回傳列表中包含指定屬性名稱與值的項目索引。

GetEnumerator()

取得一個列舉器。List

GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetItemProperties(PropertyDescriptor[])

擷取一組 PropertyDescriptor 代表資料來源清單類型可綁定屬性的物件陣列。

GetLifetimeService()
已淘汰.

取得目前控制此實例生命週期政策的終身服務物件。

(繼承來源 MarshalByRefObject)
GetListName(PropertyDescriptor[])

會取得提供綁定資料的清單名稱。

GetRelatedCurrencyManager(String)

取得指定資料成員相關的貨幣管理器。

GetService(Type)

回傳一個由 或Component其 所提供的Container服務的物件。

(繼承來源 Component)
GetType()

取得目前實例的 Type

(繼承來源 Object)
IndexOf(Object)

搜尋指定的物件,並回傳整個清單中首次出現的索引。

InitializeLifetimeService()
已淘汰.

取得一個終身服務物件以控制此實例的終身政策。

(繼承來源 MarshalByRefObject)
Insert(Int32, Object)

在指定的索引處將項目插入清單。

MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立一個 MarshalByRefObject 目前物件的淺層複製品。

(繼承來源 MarshalByRefObject)
MoveFirst()

移到清單的第一項。

MoveLast()

移到清單的最後一項。

MoveNext()

然後進入清單中的下一個項目。

MovePrevious()

移到列表中的前一項。

OnAddingNew(AddingNewEventArgs)

引發 AddingNew 事件。

OnBindingComplete(BindingCompleteEventArgs)

引發 BindingComplete 事件。

OnCurrentChanged(EventArgs)

引發 CurrentChanged 事件。

OnCurrentItemChanged(EventArgs)

引發 CurrentItemChanged 事件。

OnDataError(BindingManagerDataErrorEventArgs)

引發 DataError 事件。

OnDataMemberChanged(EventArgs)

引發 DataMemberChanged 事件。

OnDataSourceChanged(EventArgs)

引發 DataSourceChanged 事件。

OnListChanged(ListChangedEventArgs)

引發 ListChanged 事件。

OnPositionChanged(EventArgs)

引發 PositionChanged 事件。

Remove(Object)

會從清單中移除指定的項目。

RemoveAt(Int32)

移除清單中指定索引的項目。

RemoveCurrent()

將當前項目從列表中移除。

RemoveFilter()

移除與 BindingSource相關聯的濾波器。

RemoveSort()

移除與 BindingSource相關聯的排序。

ResetAllowNew()

重新初始化該 AllowNew 屬性。

ResetBindings(Boolean)

會讓綁定到的 BindingSource 控制項重新讀取清單中的所有項目並刷新它們的顯示值。

ResetCurrentItem()

會讓一個控制項綁定到 , BindingSource 重新讀取目前選取的項目並刷新其顯示值。

ResetItem(Int32)

會讓綁定到的 BindingSource 控制項在指定索引處重新讀取該項目,並刷新其顯示值。

ResumeBinding()

恢復資料綁定。

SuspendBinding()

暫停資料綁定,以防止變更更新綁定的資料來源。

ToString()

回傳 String 包含 的名稱 Component(若有的話)。 不應該覆寫這個方法。

(繼承來源 Component)

事件

名稱 Description
AddingNew

發生在項目加入底層清單之前。

BindingComplete

當所有客戶端都綁定到這個 BindingSource時,就會發生。

CurrentChanged

當目前綁定的物品改變時會發生。

CurrentItemChanged

當房產價值 Current 發生變動時。

DataError

當貨幣相關的例外被 靜默處理 BindingSource時,會發生。

DataMemberChanged

發生於 DataMember 屬性值變更時。

DataSourceChanged

發生於 DataSource 屬性值變更時。

Disposed

當元件被呼叫方法 Dispose() 時會發生。

(繼承來源 Component)
ListChanged

當底層清單變更或清單中的項目改變時,會發生這種情況。

PositionChanged

發生在房產價值 Position 變動之後。

明確介面實作

名稱 Description
IBindingList.AddIndex(PropertyDescriptor)

將 加入 PropertyDescriptor 用於搜尋的索引中。

IBindingList.RemoveIndex(PropertyDescriptor)

將 從用於搜尋的索引中移除。PropertyDescriptor

ICancelAddNew.CancelNew(Int32)

從收藏中丟棄待處理的新項目。

ICancelAddNew.EndNew(Int32)

將一個待處理的新項目提交到收藏中。

ISupportInitialize.BeginInit()

表示 BindingSource 初始化正在開始。

ISupportInitialize.EndInit()

表示 BindingSource 初始化已完成。

ISupportInitializeNotification.Initialized

當 被 BindingSource 初始化時發生。

ISupportInitializeNotification.IsInitialized

會得到一個值,表示是否 BindingSource 已被初始化。

擴充方法

名稱 Description
AsParallel(IEnumerable)

啟用查詢的平行處理。

AsQueryable(IEnumerable)

IEnumerable 轉換成 IQueryable

Cast<TResult>(IEnumerable)

IEnumerable 的項目轉換成指定的型別。

OfType<TResult>(IEnumerable)

根據指定的型別篩選 IEnumerable 的專案。

適用於

另請參閱