Upload
nicholas-porter
View
223
Download
2
Embed Size (px)
Citation preview
DEV397
Windows Forms Databinding
Mike Henderlight
Program Manager
Windows Forms
Microsoft Corporation
Agenda
Introduction
Basics
Writing a data source
Databinding Goals
Enable databinding to anything:Lists
Indexed Collections (IList)
DataSets
Data Items Business objects
*Any* object
Make Control Development easier /more consistent
Assumptions
“Three tier” is the driving scenarioDisconnected data
Finite numbers of records
Datasources all shareIndexable collections
Consistent programming model
Each List is homogeneous
ExamplesDataSet
Web Service returning an array of objects
Basics. . .
What is databinding?
Automatic display & update of dataReduces the amount of “boilerplate” code you have to write
Change notificationAutomatically updating data source from controls
Automatically updating controls from datasource
Managing the "current item"
Types of databinding
“Simple databinding”Property to property
Control has no knowledge of bindingStandard across all controls
Example: TextBox1.Text to Customer.Name
“Complex databinding”Binding to the List
Control has knowledge of binding Control dependent
Example: DataGrid1.DataSource = Customers
Types of DatasourceArray
No change notification so:No Add/DeleteLimited update
Assumes "binding type" is array type
IList (ArrayList, CollectionBase)No change notification so:
No Add/DeleteLimited update
Assumes "binding type" is:indexed accessor type or first item in the list type
Dim customers() As CustomerDim customers() As Customer
public Customer this[int index] { get; }public Customer this[int index] { get; }Default Public ReadOnly Property Item(index As Integer) As Default Public ReadOnly Property Item(index As Integer) As CustomerCustomer
Types of Datasource
IBindingListChange Notification so:
Add
Delete
Update
Sorting
Searching
Example: DataView
Binding Managers
CurrencyManagerManages binding for a list Manages the "current" item Raises CurrentChanged and PositionChanged eventsControls get “bindable list” from CurrencyManagerPoint of "consumer access"
PropertyManagerSimilar to CurrencyManager but for single object
Binding Managers
BindingContext Manages CurrencyManagers and PropertyManagers
Typically for a Form
For all contained controls
Creates CurrencyManagers and PropertyManagers
On demand based on a DataSource and a DataMember
Controls get CurrencyManager from BindingContext
Manages hierarchical relationships Based on DataMember
Enables Master-Details
44SetSet
22
SetSet
BindingContext
CurrencyManager
Binding
How it works. . .
DataSource
Customers[0].Name = “Bill”Customers[0].Name = “Bill”
11TextChangedTextChanged
22
ValidatedValidated
33SetSet
22ChangedChanged
11 SetSet
33
CurrentChangedCurrentChanged
11
What do you care about?Datasource: Property/ListChanged event
Causes control value to update
Control: PropertyChanged event Causes Binding to be marked as dirty
Control: Validated event Causes new value to be pushed to data source Can stop this using CausesValidation property
BindingContext:Get CurrencyManager for DataSource/DataMember
CurrencyManager:Position: Changes current itemBegin/End/CancelCurrent: Controls update of datasourceList: Get the data sourceCurrent: Get the "current item"CurrentChanged/Position Changed events
Binding BasicsBinding Basics
Using the Using the CurrencyManagerCurrencyManager
demodemo
Tips and Tricks
BindingContext:DataSource/DataMember is a key Different DS/DM means different CurrencyManager
Validation:Driven by Leave eventDoes happen for Menus, ToolbarCan force using Form.Validate
EndCurrentEdit:Required to flush datasource
Me.BindingManager(dataSet1, “Customers”)Me.BindingManager(dataSet1, “Customers”)DOES NOT EQUAL DOES NOT EQUAL
Me.BindingManager(dataSet1.Customers)Me.BindingManager(dataSet1.Customers)
Master-Details (DataSet)
Dataset: Bind thro’ the relationships:
BindingContext creates a RelatedCurrencyManager
DataGrid1.DataSource = DataSet1DataGrid1.DataSource = DataSet1DataGrid1.DataMember = “Customers”DataGrid1.DataMember = “Customers”
DataGrid2.DataSource = DataSet1DataGrid2.DataSource = DataSet1DataGrid2.DataMember = “Customers.CustOrders” DataGrid2.DataMember = “Customers.CustOrders”
DataGrid1.DataSource = DataSet1DataGrid1.DataSource = DataSet1DataGrid1.DataMember = _ DataGrid1.DataMember = _ “ “Customers.CustOrders.OrderOrderItems”Customers.CustOrders.OrderOrderItems”
Customers
Orders
OrderItems
CustOrdersCustOrders
OrderOrderItemsOrderOrderItems
Master-Details (Objects)
List: Bind thro’ the property names:
BindingContext creates a RelatedCurrencyManager
DataGrid1.DataSource = MyCustomersListDataGrid1.DataSource = MyCustomersListDataGrid1.DataMember = “Customers”DataGrid1.DataMember = “Customers”
DataGrid2.DataSource = MyCustomersListDataGrid2.DataSource = MyCustomersListDataGrid2.DataMember = “Customers.Orders” DataGrid2.DataMember = “Customers.Orders”
DataGrid1.DataSource = MyCustomersListDataGrid1.DataSource = MyCustomersListDataGrid1.DataMember = “Customers.Orders.OrderItems”DataGrid1.DataMember = “Customers.Orders.OrderItems”
Customers
Orders(OrdersCollection)
OrderItems(OrderItemsCollection)
Master-DetailsMaster-Details
demodemo
Lookup table
You can use a ComboBox or ListBox as a “lookup” table
Example: State field in Customer objectBind ComboBox to States collection
Set DisplayValue to “value” property name
Bind SelectedValue to Customer.State
ComboBox1.DataSource = MyStatesComboBox1.DataSource = MyStatesComboBox1.DisplayMember = “LongName”ComboBox1.DisplayMember = “LongName”ComboBox1.ValueMember = “ShortName”ComboBox1.ValueMember = “ShortName”
ComboBox1.DataBindings.Add _ComboBox1.DataBindings.Add _ (“SelectedValue”, DataSet1, “Customers.State”)(“SelectedValue”, DataSet1, “Customers.State”)
Lookup TableLookup Table
demodemo
Formatting
Example: Format 12 as $12.00
Use the Format and Parse events on the Binding:
Format and Parse are “paired” You need to do both
Use BCL Formatting to actually format the value
AddHandler TextBox1.DataBindings("Text").Format, _AddHandler TextBox1.DataBindings("Text").Format, _ AddressOf Me.TextBox1_FormatAddressOf Me.TextBox1_Format
textBox1.DataBindings["Text"].Format textBox1.DataBindings["Text"].Format +=new ConvertEventHandler(Form1_Format);+=new ConvertEventHandler(Form1_Format);
FormattingFormatting
demodemo
Displaying errors
You can set errors on the DataSet:
Use ErrorProvider to display this information
DataGrid automatically displays this information
Use IDataErrorInfo on your business objects
TIP: Don’t throw exceptions. We eat them!
row.RowError = "You need to update the Widget price"row.RowError = "You need to update the Widget price"row.SetColumnError("WidgetPrice", “Bad Widget Price")row.SetColumnError("WidgetPrice", “Bad Widget Price")
Displaying ErrorsDisplaying Errors
demodemo
Tips and Tricks (2)
Datasets:You always bind to a DataView but not to the DefaultView
The DataSet generates them on demand
You can get to the DataView thro’ the CurrencyManager
Use a DataViewManager to apply default Sorts and Filters
Esp. useful for “child views” in a Master-Details Form
Using a Using a DataViewManagerDataViewManager
demodemo
Writing a Data Source. . .
Datasource InterfacesData Lists
IList – indexed list
IBindingList – list that supports change events
searchable
sortable
IListSource – object that returns a list
ITypedList – list with schema
Data ItemsIEditableObject – Commit/Cancel
IDataErrorInfo – error information
ICustomTypeDescriptor – custom type information
IBindingListWe will focus on change notification, Add, Remove, Update:
public interface IBindingList : IList { public interface IBindingList : IList { // Properties // Properties bool bool AllowEditAllowEdit { get; } { get; } bool bool AllowNewAllowNew { get; } { get; } bool bool AllowRemoveAllowRemove { get; } { get; }. . . . . . bool bool SupportsChangeNotificationSupportsChangeNotification { get; } { get; }. . . . . . // Events // Events public event ListChangedEventHandler public event ListChangedEventHandler ListChangedListChanged;;
// Methods // Methods. . .. . . object object AddNewAddNew();();. . .. . .}}
Writing a custom Writing a custom data sourcedata source
demodemo
Community Resources
Community Resourceshttp://www.microsoft.com/communities/default.mspx
Most Valuable Professional (MVP)http://www.mvp.support.microsoft.com/
NewsgroupsConverse online with Microsoft Newsgroups, including Worldwidehttp://www.microsoft.com/communities/newsgroups/default.mspx
User GroupsMeet and learn with your peershttp://www.microsoft.com/communities/usergroups/default.mspx
evaluationsevaluations
© 2003 Microsoft Corporation. All rights reserved.© 2003 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.This presentation is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS OR IMPLIED, IN THIS SUMMARY.