BindingList<T>
Class
Definition
Provides a generic collection that supports data binding.
public class BindingList<T> : System.Collections.ObjectModel.Collection<T>, System.ComponentModel.IBindingList, System.ComponentModel.ICancelAddNew, System.ComponentModel.IRaiseItemChangedEvents
- T
The type of elements in the list.
- Inheritance
- Implements
Inherited Members
System.Collections.ObjectModel.Collection`1
System.Object
Examples
The following code example demonstrates binding to a BindingList<T> component containing a business object. This is a complete example that contains a Main method.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace BindingListOfTExamples
{
public partial class Form1 : Form
{
private TextBox textBox2;
private ListBox listBox1;
private Button button1;
private TextBox textBox1;
Random randomNumber = new Random();
public Form1()
{
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.listBox1 = new System.Windows.Forms.ListBox();
this.button1 = new System.Windows.Forms.Button();
this.textBox1.Location = new System.Drawing.Point(169, 26);
this.textBox1.Size = new System.Drawing.Size(100, 20);
this.textBox1.Text = "Bracket";
this.textBox2.Location = new System.Drawing.Point(169, 57);
this.textBox2.ReadOnly = true;
this.textBox2.Size = new System.Drawing.Size(100, 20);
this.textBox2.Text = "4343";
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(12, 12);
this.listBox1.Size = new System.Drawing.Size(120, 95);
this.button1.Location = new System.Drawing.Point(180, 83);
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.Text = "Add New Item";
this.button1.Click += new System.EventHandler(this.button1_Click);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.button1);
this.Controls.Add(this.listBox1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this.Text = "Parts Form";
this.Load += new EventHandler(Form1_Load);
}
void Form1_Load(object sender, EventArgs e)
{
InitializeListOfParts();
listBox1.DataSource = listOfParts;
listBox1.DisplayMember = "PartName";
listOfParts.AddingNew += new AddingNewEventHandler(listOfParts_AddingNew);
listOfParts.ListChanged += new ListChangedEventHandler(listOfParts_ListChanged);
}
// Declare a new BindingListOfT with the Part business object.
BindingList<Part> listOfParts;
private void InitializeListOfParts()
{
// Create the new BindingList of Part type.
listOfParts = new BindingList<Part>();
// Allow new parts to be added, but not removed once committed.
listOfParts.AllowNew = true;
listOfParts.AllowRemove = false;
// Raise ListChanged events when new parts are added.
listOfParts.RaiseListChangedEvents = true;
// Do not allow parts to be edited.
listOfParts.AllowEdit = false;
// Add a couple of parts to the list.
listOfParts.Add(new Part("Widget", 1234));
listOfParts.Add(new Part("Gadget", 5647));
}
// Create a new part from the text in the two text boxes.
void listOfParts_AddingNew(object sender, AddingNewEventArgs e)
{
e.NewObject = new Part(textBox1.Text, int.Parse(textBox2.Text));
}
// Add the new part unless the part number contains
// spaces. In that case cancel the add.
private void button1_Click(object sender, EventArgs e)
{
Part newPart = listOfParts.AddNew();
if (newPart.PartName.Contains(" "))
{
MessageBox.Show("Part names cannot contain spaces.");
listOfParts.CancelNew(listOfParts.IndexOf(newPart));
}
else
{
textBox2.Text = randomNumber.Next(9999).ToString();
textBox1.Text = "Enter part name";
}
}
void listOfParts_ListChanged(object sender, ListChangedEventArgs e)
{
MessageBox.Show(e.ListChangedType.ToString());
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new Form1());
}
}
// A simple business object for example purposes.
public class Part
{
private string name;
private int number;
public Part() { }
public Part(string nameForPart, int numberForPart)
{
PartName = nameForPart;
PartNumber = numberForPart;
}
public string PartName
{
get { return name; }
set { name = value; }
}
public int PartNumber
{
get { return number; }
set { number = value; }
}
}
}
Option Explicit On
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Class Form1
Inherits Form
Private textBox2 As TextBox
Private listBox1 As ListBox
Private WithEvents button1 As Button
Private textBox1 As TextBox
Private randomNumber As New Random()
Public Sub New()
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.textBox1 = New System.Windows.Forms.TextBox()
Me.textBox2 = New System.Windows.Forms.TextBox()
Me.listBox1 = New System.Windows.Forms.ListBox()
Me.button1 = New System.Windows.Forms.Button()
Me.textBox1.Location = New System.Drawing.Point(169, 26)
Me.textBox1.Size = New System.Drawing.Size(100, 20)
Me.textBox1.Text = "Bracket"
Me.textBox2.Location = New System.Drawing.Point(169, 57)
Me.textBox2.ReadOnly = True
Me.textBox2.Size = New System.Drawing.Size(100, 20)
Me.textBox2.Text = "4343"
Me.listBox1.FormattingEnabled = True
Me.listBox1.Location = New System.Drawing.Point(12, 12)
Me.listBox1.Size = New System.Drawing.Size(120, 95)
Me.button1.Location = New System.Drawing.Point(180, 83)
Me.button1.Size = New System.Drawing.Size(75, 23)
Me.button1.Text = "Add New Item"
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.button1)
Me.Controls.Add(Me.listBox1)
Me.Controls.Add(Me.textBox2)
Me.Controls.Add(Me.textBox1)
Me.Text = "Parts Form"
AddHandler Me.Load, AddressOf Form1_Load
End Sub 'New
Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
InitializeListOfParts()
listBox1.DataSource = listOfParts
listBox1.DisplayMember = "PartName"
End Sub
' Declare a new BindingListOfT with the Part business object.
Private WithEvents listOfParts As BindingList(Of Part)
Private Sub InitializeListOfParts()
' Create the new BindingList of Part type.
listOfParts = New BindingList(Of Part)
' Allow new parts to be added, but not removed once committed.
listOfParts.AllowNew = True
listOfParts.AllowRemove = False
' Raise ListChanged events when new parts are added.
listOfParts.RaiseListChangedEvents = True
' Do not allow parts to be edited.
listOfParts.AllowEdit = False
' Add a couple of parts to the list.
listOfParts.Add(New Part("Widget", 1234))
listOfParts.Add(New Part("Gadget", 5647))
End Sub
' Create a new part from the text in the two text boxes.
Private Sub listOfParts_AddingNew(ByVal sender As Object, _
ByVal e As AddingNewEventArgs) Handles listOfParts.AddingNew
e.NewObject = New Part(textBox1.Text, Integer.Parse(textBox2.Text))
End Sub
' Add the new part unless the part number contains
' spaces. In that case cancel the add.
Private Sub button1_Click(ByVal sender As Object, _
ByVal e As EventArgs) Handles button1.Click
Dim newPart As Part = listOfParts.AddNew()
If newPart.PartName.Contains(" ") Then
MessageBox.Show("Part names cannot contain spaces.")
listOfParts.CancelNew(listOfParts.IndexOf(newPart))
Else
textBox2.Text = randomNumber.Next(9999).ToString()
textBox1.Text = "Enter part name"
End If
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
' A simple business object for example purposes.
Public Class Part
Private name As String
Private number As Integer
Public Sub New()
End Sub
Public Sub New(ByVal nameForPart As String, _
ByVal numberForPart As Integer)
PartName = nameForPart
PartNumber = numberForPart
End Sub
Public Property PartName() As String
Get
Return name
End Get
Set(ByVal value As String)
name = Value
End Set
End Property
Public Property PartNumber() As Integer
Get
Return number
End Get
Set(ByVal value As Integer)
number = Value
End Set
End Property
End Class
Remarks
The BindingList<T> class can be used as a base class to create a two-way data-binding mechanism. BindingList<T> provides a concrete, generic implementation of the IBindingList interface. This is an alternative to implementing the complete IBindingList interface, which can be difficult because of the subtle interaction between IBindingList, IEditableObject, and the associated CurrencyManager. However, the typical solutions programmer will use a class that provides data binding functionality, such as BindingSource, instead of directly using BindingList<T>.
BindingList<T> supports factory-created instances through the extensible AddNew method. (This same type of extensibility is also found in other classes, such as BindingSource) In addition, since this class implements the ICancelAddNew interface, it enables transactional commits or rollbacks of the new item through the EndNew and CancelNew methods.
Constructors
| BindingList<T>() |
Initializes a new instance of the BindingList<T> class using default values. |
| BindingList<T>(IList<T>) |
Initializes a new instance of the BindingList<T> class with the specified list. |
Properties
| AllowEdit |
Gets or sets a value indicating whether items in the list can be edited. |
| AllowNew |
Gets or sets a value indicating whether you can add items to the list using the AddNew() method. |
| AllowRemove |
Gets or sets a value indicating whether you can remove items from the collection. |
| IsSortedCore |
Gets a value indicating whether the list is sorted. |
| RaiseListChangedEvents |
Gets or sets a value indicating whether adding or removing items within the list raises ListChanged events. |
| SortDirectionCore |
Gets the direction the list is sorted. |
| SortPropertyCore |
Gets the property descriptor that is used for sorting the list if sorting is implemented in a derived class; otherwise, returns |
| SupportsChangeNotificationCore |
Gets a value indicating whether ListChanged events are enabled. |
| SupportsSearchingCore |
Gets a value indicating whether the list supports searching. |
| SupportsSortingCore |
Gets a value indicating whether the list supports sorting. |
Methods
| AddNew() |
Adds a new item to the collection. |
| AddNewCore() |
Adds a new item to the end of the collection. |
| ApplySortCore(PropertyDescriptor, ListSortDirection) |
Sorts the items if overridden in a derived class; otherwise, throws a NotSupportedException. |
| CancelNew(Int32) |
Discards a pending new item. |
| ClearItems() |
Removes all elements from the collection. |
| EndNew(Int32) |
Commits a pending new item to the collection. |
| FindCore(PropertyDescriptor, Object) |
Searches for the index of the item that has the specified property descriptor with the specified value, if searching is implemented in a derived class; otherwise, a NotSupportedException. |
| InsertItem(Int32, T) |
Inserts the specified item in the list at the specified index. |
| OnAddingNew(AddingNewEventArgs) |
Raises the AddingNew event. |
| OnListChanged(ListChangedEventArgs) |
Raises the ListChanged event. |
| RemoveItem(Int32) |
Removes the item at the specified index. |
| RemoveSortCore() |
Removes any sort applied with ApplySortCore(PropertyDescriptor, ListSortDirection) if sorting is implemented in a derived class; otherwise, raises NotSupportedException. |
| ResetBindings() |
Raises a ListChanged event of type Reset. |
| ResetItem(Int32) |
Raises a ListChanged event of type ItemChanged for the item at the specified position. |
| SetItem(Int32, T) |
Replaces the item at the specified index with the specified item. |
Events
| AddingNew |
Occurs before an item is added to the list. |
| ListChanged |
Occurs when the list or an item in the list changes. |
Explicit Interface Implementations
| IBindingList.AddIndex(PropertyDescriptor) |
For a description of this member, see AddIndex(PropertyDescriptor). |
| IBindingList.AddNew() |
Adds a new item to the list. For more information, see AddNew(). |
| IBindingList.AllowEdit |
Gets a value indicating whether items in the list can be edited. |
| IBindingList.AllowNew |
Gets a value indicating whether new items can be added to the list using the AddNew() method. |
| IBindingList.AllowRemove |
Gets a value indicating whether items can be removed from the list. |
| IBindingList.ApplySort(PropertyDescriptor, ListSortDirection) |
Sorts the list based on a PropertyDescriptor and a ListSortDirection. For a complete description of this member, see ApplySort(PropertyDescriptor, ListSortDirection). |
| IBindingList.Find(PropertyDescriptor, Object) |
For a description of this member, see Find(PropertyDescriptor, Object). |
| IBindingList.IsSorted |
For a description of this member, see IsSorted. |
| IBindingList.RemoveIndex(PropertyDescriptor) |
For a description of this member, see RemoveIndex(PropertyDescriptor). |
| IBindingList.RemoveSort() |
For a description of this member, see RemoveSort() |
| IBindingList.SortDirection |
For a description of this member, see SortDirection. |
| IBindingList.SortProperty |
For a description of this member, see SortProperty. |
| IBindingList.SupportsChangeNotification |
For a description of this member, see SupportsChangeNotification. |
| IBindingList.SupportsSearching |
For a description of this member, see SupportsSearching. |
| IBindingList.SupportsSorting |
For a description of this member, see SupportsSorting. |
| IRaiseItemChangedEvents.RaisesItemChangedEvents |
Gets a value indicating whether item property value changes raise ListChanged events of type ItemChanged. This member cannot be overridden in a derived class. |