Analysis of data binding mechanism of ADO.NET and its application

xiaoxiao2021-03-06  37

This is part of the book I wrote, all original, just completed, welcome to comment.

Bitfan

-------------------------------------------------- -----

7.5.2 Move in data concentration

When you need to display multiple records in the program, we often hope to record a "record number" to facilitate location records, such as "to the first", "to the last", "jump to item 100" ... .

The record in DataTable (ie DATAROW) itself does not have a so-called "record number", and DataTable itself does not provide this feature.

prompt:

In VB6, record set object Recordset provides MoveFirst, MoveLast et al. This is achieved by ADO. In ADO.NET, DataTable and Datarow have no these methods.

At first glance, you can't move in the data set, as if it is an omission of ADO.NET design. In fact, ADO.NET extracts all the functions located in the data set, plus other features, builds the data binding mechanism of ADO.NET, compared to the limited positioning function provided by the original ADO, ADO. Net is more powerful and flexible.

Please try to run the example moveindataable in this book's condomation CD, and its running interface is shown in Figure 7-15:

Figure 7-15 Data Binding Example

When this program is running, you can click on the four buttons in the bottom right, or you can directly click on the upper grid to move in the data set, and the current row is displayed in the two text boxes in the lower part. Data can be modified directly in the text box. When moving to other rows, the records in the grid are simultaneously refreshed.

Through this example, we come to analyze the principles of data binding mechanisms in ADO.NET.

1 What is the data binding?

The so-called data binding, it is popular, that is, take the data in the data source (such as a DataTable), displayed on various controls of the form, users can view and modify data through these controls, these modifications will automatically save them. In the data source, see Figure 7-16.

Figure 7-16 Principle of data binding

Windows Forms can utilize two types of data bindings: simple binding and complex binding. These two types have different advantages.

l Simple binding

Simple data binding refers to the ability to bind a control to a single data element (such as the value in the column of the data set table). This is a typical binding type for controls such as TextBox controls or Label controls (ie, only controls that only display a single value). Two text boxes in Figure 7-15 bound to "AddressStr" and "ClientName" in DataTable.

l Complex binding

Complex data binding refers to the ability to bind a control to multiple data elements, typically binding multiple records in the database. The DataGrid in Figure 7-15 is bound to a DataTable, which can display a number of records and multiple fields at a time.

2 implementation in data concentration

Move in data concentration is a sub function in a data binding mechanism.

In order to facilitate understanding of the complex data binding mechanism in ADO.NET, we first implemented data mobile features in a simple form in the MoveindATABLE example, see Figure 7-17:

Figure 7-17 Manual implementation moves in recording

The following is analyzed

(1) The program needs to extract data, the SUB process getData implements this feature:

'Define related variables

PRIVATE CONN AS OLEDBCONNECTION

Private comm as oledbcommand

Private Da As OledbdataAdapterPrivate DS1 AS New DataSet

'retrieve data

Private sub getdata ()

'Creating a connection object connection database

CONN = New OLEDBCONNECTION

Conn.connectionstring = "provider = microsoft.jet.Oledb.4.0; data source = d: /clients.mdb; persist security info = false

Conn.open ()

'Creating a command object Used to send a SQL command to the database

Comm = New OLEDBCommand

Comm.commandtext = "SELECT * from OrderClient"

Comm.commandType = CommandType.Text

Comm.connection = conn

'Creating DataAdapter to populate DataSet

Da = New OLEDBDataAdapter (Comm)

'Data input

Da.fill (DS1)

CONN.CLOSE ()

End Sub

Note that it is assumed that the database clients.mdb is placed under "D: /". We are already very familiar with these code.

(2) Set the data binding, the SUB process setDataBing () implements this feature:

'Data Binding Management Object

Private cm as currencymanager

'Setting data binding

Private sub setDataBinding ()

'Bind DataGrid to DATATABLE

Me.DataGrid1.datasource = DS1.TABLES (0)

'Get data binding management objects

cm = me.bindingcontext (ds1.tables (0))

End Sub

In the second form of the sample program (see Figure 7-15), it is only more than the code that binds the text box to the field in the DataTable:

Me.TxtAddress.Databindings.add ("text", ds1.tables (0), "addressstr")

Me.txtName.DataBindings.add ("Text", DS1.Tables (0), "ClientName")

It can be seen that the data binding to the DataGrid is very simple, just set it directly to the DataSource property.

Set the data binding to the text box, you need to add an item to its DataBindings, which is:

"The property name to be bound", the bound DATATABLE object, "DataTable field name"

In the above code, the control is binding directly to the DataTable, in fact, you can also bind to DataSet directly, but you need some changes to the code:

'Bind DataGrid to DATATABLE

Me.DataGrid1.datasource = DS1

Me.DataGrid1.dataMember = ds1.tables (0) .tablename

'Binding text box

Me.txtaddress.databindings.add ("Text", DS1, DS1.TABLES (0) .tablename & ".addressStr")

Me.txtName.Database.dd ("text", ds1, ds1.tables (0) .tablename & ".clientname") Because there may be multiple DataTable in DataSet, you must specify a table name to DataGrid's DataMember attribute . Dynamically specify a DataTable table name in the program, you can dynamically bind the DataTable with the DataGrid corresponding to this table name.

The third parameter bound by the text box is called a "binding string", separated by English sentence, its format:

Table name. Field name

It is characterized by the larger the scope of the loop on the left.

Technical inside:

In fact, data binding is not limited to DataSet and DataTable, which can also bind text boxes and DataGRIDs to other objects, such as arrays and arraylist, at this time, binding strings are very important, interested readers can be in MSDN By searching for "Data Binding" keywords how to bind to non-Dataset and DataTable data.

(3) It is now possible to move in the record set, which is implemented by assigning the current property of the CurrencyManager, and the key code is listed below:

'Move to the first

cm.position = 0

'Move to the previous one

IF cm.position> 0 THEN

cm.position - = 1

END IF

'Move to the next

IF cm.position

cm.position = 1

END IF

'Move to the last

cm.position = cm.count - 1

It can be seen that movement is implemented by the CurrencyManager object in the data set.

Although the code is simple, if it does not understand the mechanism behind this, it is still unable to fully utilize the data binding mechanism.

3 data binding principle

ADO.NET's data binding mechanism is mainly composed of the following classes:

Figure 7-18 Data Binding Class

Figure 7-18 shows the core architecture of data binding in ADO.NET (note that all classes are not integrated) in the UML montage.

prompt:

UML is referred to as Unified Modeling Language (Unified Modeling Language), which uses graphical ways to express object-oriented software system architectures, and have been widely accepted by software industry and become international standards. Part IV Part of this book introduces a large number of UML clanographed programming programming in object-oriented programming. There is a UML basic tutorial in the appendix of this book, which is available for readers.

Now introduce each class one by one.

From the example we already know, the controls such as text box can be bound to the field, this fact itself contains the following information:

The own attribute to be bound (such as Text Attribute)

Available in data sources (such as DataTable)

Bind navigation string

..........

This information is encapsulated and forms a Binding class. Each control that implements data binding has at least one Binding object, indicating its binding information.

There may be multiple controls on a form (such as a plurality of text boxes) bind to a data source, which means that there are multiple Binding objects. Therefore, there is a class to manage these objects. This class is a BindingManagerBase class, but this class is an abstract class. You cannot create an object directly. CurrencyManager directly inherit from the BindingManagerBase class, implement all the basic classes that are not implemented, can be used directly . The function moved in the data set is implemented by the CurrencyManager object. Now I know, I want to move in the data set, I have to get the CurrencyManager object corresponding to this dataset. How do you do this?

A form will not only have multiple controls (such as multiple text boxes) bind to a data source, and there may be a case where multiple controls are bound to multiple data sources (assuming two DataSets in the form, respectively Provides data for two sets of controls, there are two CurrencyManager objects in the form), so a class is designed to manage these CurrencyManager objects, which is the function of the BindingContext class. There will be at least one BindingContext object on each form of data binding.

Summary now:

Gets the BindingContext object à by the BindingContext object à through the CurrencyManager object to implement the function in the recordset

This is the insider that implements the mobile function in the data set.

Said so much, in fact, only one sentence in the sample code:

'Data Binding Management Object

Private cm as currencymanager

'..........

'Get data binding management objects

cm = me.bindingcontext (ds1.tables (0))

Self-exploration:

A container control, such as Form, GroupBox, and TabControl, you can have your own BindingContext object. The following code sets two Groupbox's BindingContext object:

DIM BCG1 AS New BindingContext ()

DIM BCG2 As New BindingContext ()

Groupbox1.bindingContext = BCG1

Groupbox2.bindingContext = BCG2

Please design an app with two GroupBox, and some data binding controls are available in each GroupBox, which is programmed to implement data from different locations in the same data source.

3 Design data binding auxiliary class

As can be seen from the above, the data binding function provided by ADO.NET is flexible, but it is indeed too complicated and is not easy to use, and the function of moving in the data set is very common if in each form. Repeat these codes, it is really boring and boring. Therefore, these code can be encapsulated as a data binding assisted class. The DataBindingHelper class is created for this purpose.

First define some of the members variables of the class:

'Internal binding manager

Private _cm as currencymanager = nothing

'The internal binding control container is usually the form

Private _Container as Control = Nothing

'Revealing the currencymanager object to the outside world

Public Readonly Property cm () AS CurrencyManager

Get

Return_cm

END GET

End Property 'Container Control

Public property container () AS Control

Get

Return_Container

END GET

Set (ByVal Value As Control)

_Container = Value

End set

End Property

Then you need to provide a method to specify the data source:

'Data source properties, you can specify DataMember, or you can omit, for DataTable

Public SUB setDataSource (byval DataSource As Object, Optional Byval DataMember AS String = Nothing)

IF _Container is nothing then

MSGBOX ("Please specify control containers first")

EXIT SUB

END IF

If DataMember is nothing then

_cm = _Container.BindingContext (Datasource)

Else

_cm = _Container.BindingContext (DataSource, DataMember)

END IF

End Sub

Now you can achieve your mobile function, and then move a record as an example:

Public Sub Movenext ()

'_cm is not created or empty, all exit

IF_cm is nothing then

EXIT SUB

END IF

IF _CM.COUNT = 0 THEN

EXIT SUB

END IF

IF _CM.Position <_cm.count - 1 THEN

_cm.position = 1

END IF

End Sub

With the DataBindingHelper class, it is very simple to move in the data set. The following is the code in the sample project:

Dim DBH1 As New DataBindingHelper

'Set the container object as the form

DBH1.CONTAINER = ME

'Setting the data source

DBH1.SetDataSource (ds1.tables (0))

The mobile code is as follows:

Private sub btnmovefirst1_click (...) Handles btnmovefirst1.click

DBH1.MOVEFIRST ()

End Sub

PRIVATE SUB BTNMOVEPREV_CLICK (...) Handles BtnmovePrev.click

DBH1.MOVEPREV ()

End Sub

Is it very simple?

I believe that you can understand the benefits of object-oriented technology!

转载请注明原文地址:https://www.9cbs.com/read-61044.html

New Post(0)