C # BindingSource Class

Source: Internet
Author: User

?

1. Introduction

??

The BindingSource component is a bridge between the data source and the control, and provides a number of APIs and event information for our use. Using these APIs, we can decouple code from a variety of specific types of data sources, and with these events we can gain insight into the changes in the data.

2. Simple Binding

??

???????? A DataTable? MyTable? =? Mytableadapter.getdata ();//CREATE TABLE

??

???????? BindingSource? Mybindingsource=? New?? BindingSource ();//Create BindingSource

??

???????? DataGridView? Mygrid? =? New?? DataGridView ();//Create GridView

??

???????? Mygrid.datasource? =? mybindingsource;//binding BindingSource to the GridView

??

???????? mytable;//bind data to BindingSource

??

???????? Note:

??

???????? 1) binding to a DataTable is actually bound to the DataView provided by the DataTable. Each DataTable has a default DataView

??

???????? 2) DataView is the essence of binding, as its name is, it is the presentation of data in a DataTable. Therefore, the same DataTable can be

??

????????, build multiple DataView, and then you can implement different filtering and sorting methods for the same data, and display the DataTable from different sides. This also embodies a certain degree of MVC thought.

??

???????? 3) Bindingsouce can also be used as a container for data (which is actually a data reference) to be passed between different forms to enable editing of data in a popup form?

??

3. Main fine Table

??

???????? Image

??

???????? Take the data shown as an example:

??

???????? 1) Dataset:mydataset

??

???????? 2) datatable:parenttable, childtable, grandchildtable

??

???????? 3) Relation:fk_parent_child, Fk_child_grandchild

??

???????? Binding parent Data

??

???????? Parentbindingsource.datasource? =? myDataSet;

??

???????? Parentbindingsource.datamember? =? "ParentTable";

??

???????? M_grandparentgrid.datasource? =? M_grandparentbindingsource;

??

???????? Binds the child data.

???????? Childbindingsource.datasource? =? parentbindingsource;//bind to "parent BindingSource" instead of parent table

??

???????? Childbindingsource.datamember? =? "Fk_child_grandchild";//Bind to "parent-child relation"

??

???????? Bind grandson data.

???????? Grandchildbindingsource.datasource? =? childbindingsource;//binding to "sub-BindingSource"

??

???????? Grandchildbindingsource.datamember? =? "Fk_child_grandchild";//Bind to "son-sun relation"

??

This allows you to put 3 DataView on the form and distribute it to the 3 bindingsouce, which makes it easy to correlate the main fine table.

4. Data manipulation

To manipulate the data, you first need to get the current data item. The current property of BindingSource Returns an object of type DataRowView (like DataView is right?). In the case of a DataTable, DataRowView is the encapsulation of a DataRow, which is the encapsulation of the current data item and can be transformed into the object you want.

??

???????? DataRowView? Currentrowview? =? mybindingsource.current;//Get current Rowview

??

???????? CustomersRow? Custrow? =? Currentrowview.row? As?? The customersrow;//type is converted to the current data item

??

???????? String?? Company? =? custrow.companyname;//using the current data item

??

???????? String?? Phoneno? =? Custrow.phone;

??

5. Use BindingSource to make data containers

??

BindingSource can also be used as a data container, even if it is not bound to a data source, and it has a list inside it that can hold the data.

5.1Add method

??

Calling the Add method inserts a data item in the list of BindingSource. If the data is inserted for the first time, and no data is bound, then the type of data inserted determines the type of data in the list in the future.

??

???????? Note:

??

???????? 1) inserting other types of objects at this time throws a InvalidOperationException exception

??

???????? 2) The list is refreshed when the DataSource property is set, resulting in data loss from the Add method added to the list

??

5.2AddNew method

??

The AddNew method returns an object that contains the data type that the BINDINGSOURC holds, and if the data was not previously accommodated, the object is returned.

??

The AddNew method invokes the EndEdit method and commits the manipulation of the current data, and the new data item becomes the current item.

??

The AddNew method raises the AddingNew event, where you can assign a value to a data item, or create a new data item

??

???????? Private?? void?? Onaddingnew (object?? sender,? AddingNewEventArgs? E

???????? {

???????????????????? E.newobject? =? New?? Mycustomobject ();//

????????}

??

6. Use BindingSource to sort, filter, and search data

6.1? Sort

??

You can sort the data by assigning a sort expression to the Sort property

??

???????? Mybindingsource.sort? =? "ContactName?" ASC ";//Sort the Contanctname column by ASC

??

???????? Mybindingsource.sort? =? "Region?" Asc? CompanyName? DESC "//first by region, then by CompanyName

??

6.2? Find

??

???????? The Find method finds the specified attribute and keyword and returns the index of the first matching object

???????? Int?? Index? =? M_customersbindingsource.find ("CompanyName", IBM);//press CompanyName to find IBM

???????? If?? (index?! =?-1)

???????? {

???????????????? Mybindingsource.position? =? index;//positioning BindingSource

????????}

??

6.3? Filter

??

You can filter the data by assigning an expression to the Filter property

??

???????? M_customersbindingsource.filter? =? "Country?" =? ' Germany ';//filter out Data country property is Germany

??

7. Monitoring data with Event

7.1? Event

??

???????? 1) AddingNew

??

???????? triggered when the AddNew () method is called.

??

???????? 2) BindingComplete

??

???????? When the control completes the data binding trigger, the control has read the value of the current data item from the data source. This event is triggered when BindingSource is re-bound or the current data item changes

??

???????? Note:

??

???????????????? *? When multiple controls are bound to the same data source, this event fires multiple times

??

???????? 3) currrentchanged

??

???????? This event is triggered when the current data item changes. The situation where this event is triggered is as follows

??

???????????????? *? When the Position property is changed

???????????????? *? When you add or delete data

???????????????? *? DataSource or DataMember property is changed

??

???????? 4) currentitemchanged

??

???????? triggered when the value of the current data item changes

??

???????? 5) DataError

??

???????? Typically, when invalid data is entered, an exception is thrown by Currencymanage, which triggers this event.

??

???????? 6) positionchanged

??

???????? This event is triggered when the position property is changed.

??

???????? 7) ListChanged

??

???????? Triggered when the data set changes. The situation where this event is triggered is as follows

??

???????????????? *? Adding, huh? editing, huh? deleting, huh? Or? Moving? When the data item

??

???????? When changing properties that affect the list behavior characteristics, such as the AllowEdit property

??

???????????????? *? When a list is replaced (tied to a new data source)

??

8. Restricting data modification

??

BindingSource is not only the "bridge" between the data source and the control, but also the "gatekeeper" of the data source. With BindingSource, we can control the modification of the data.

??

Binidingsource's AllowEdit, huh? The AllowNew and AllowRemove properties control the modification of data by client code and controls

9. Binding of complex data types

??

For a string type of data, binding directly to the text control, there are several cases for complex types

??

???????? *? For data of types such as datetime, image, they are stored in a format that is inconsistent with the display requirements.

???????? *? Sometimes you don't want to show the customer ID, but you want to show the customer name

???????? *? Null values in the database

??

9.1? Binding class

??

The key to solving the above problem is to understand the binding class and understand how it controls the data binding process.

??

???????? A DataTable? Table? =? Customersdataset.customers;

??

???????? Binds the TextBox's Text property to the table's CustomerID column

???????? CUSTOMERIDTEXTBOX.DATABINDINGS.ADD ("Text",? Table, "CustomerID",? true);

??

???????? The line above is equivalent to the following two lines of code

??

???????? Binding? Customeridbinding? =? New?? Binding ("Text",? Table, "CustomerID", "true");

???????? CUSTOMERIDTEXTBOX.DATABINDINGS.ADD (customeridbinding);

??

As you can see from the code, the binding is the mediator between the data source (table) and the control (Customeridtextbox), which has the following functions

??

???????? *? Data is taken from the data source and formatted according to the data type required by the control (formatting), and then passed to the control

???????? *? Fetch data from the control and parse it (parsing) according to the data type requirements of the data source, and then return to the data source

???????? *? Automatic format conversion of data

??

9.2Binding class Constructors and properties

??

The binding constructor has multiple overloaded versions, and the following describes its important parameters, which exist in the properties of the binding object. In the following section, parameter names and attribute names are listed to

??

???????? 1) formattingenabled (attribute formattingenabled)

??

???????????????????? O? True,binding objects are automatically converted between the data source type and the type required by the control

???????????????????? O? False, and vice versa

??

???????? 2) DataSourceUpdateMode

??

???????? Determines when changes to a value on a control are committed back to the data source

??

???????? 3) Nullvalue

??

???????? DBNull,? The value corresponding to null and nullab<t>.

??

???????? 4) formatString

??

???????? Format conversion

??

???????? 5) FormatInfo

??

???????? An object reference that implements the IFormatProvider interface, converted with a custom format

??

To learn how types are converted, learn the type? Conversions? and? Format? Providers related content. For the application of the above attribute, see the following introduction

9.3 Type conversion based on the built-in mechanism (attributes, parameters) of the binding class

??

The mechanism of type conversion can be controlled by a parameter, or property setting, when the binding class is constructed.

??

1) DateTime

??

Let's start with an example of a datetime type using the DateTimePicker control

??

???????? Create binding, set Formattingenabled to True

??

???????? BIRTHDATETIMEPICKER.DATABINDINGS.ADD ("Value", M_employeesbindingsource,? "BirthDate",? true);

??

???????? Set to use the custom format

???????? Birthdatetimepicker.format? =? Datetimepickerformat.custom;

??

???????? Set format

???????? Birthdatetimepicker.customformat? =? "Mm/dd/yyyy";

??

2) Numeric

??

???????? SALARYTEXTBOX.DATABINDINGS.ADD ("Text",? Employeesbindingsource, "Salary",

C # BindingSource Class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.