ado| View ADO. NET contains a layer of objects to create an abstract model of any data source. which includes
dataset,datatable,datarow,dataview,datarelationWait a minute.
All of these objects are defined in the
System.DataThe name space. They form an abstract model that allows the same programming interface to be used regardless of the programming for Windows Form,web Form or Web service.
In practical applications, most of these objects operate on data in relational databases such as SQL Server. However, they can handle a variety of data, regardless of its physical storage medium.
You can use
DataSetobject to package and correlate the data in each table, using a DataTable class to work with table-type data, and
DataRowObject can work with data from a row in a table.
These three objects are packaged for data, but have different levels of logical aggregation.
DataSetIs
DataTableand other combinations. and
DataTableIs
DataRowand other combinations.
DataRowis a combination of fields and other. However, none of these objects has built-in filtering and sorting capabilities.
Ado. NET provides classes to handle important aspects of this database application. In. Net Beta2, the two most important objects in this area are
DataViewAnd
DataViewManager。
Attention: DataViewManager is peculiar to Beta2. In Beta1, the corresponding function is completed by DataSetView.
Customizing Data Views
The DataView class is used to represent custom
DataTableThe view.
DataTableAnd
DataViewThe relationship is to follow the famous design pattern--Document/view mode, where
DataTableis a document, and
Dataviewis the view.
At any time, you can have multiple different views based on the same data. More importantly, you can handle each view with its own set of attributes, methods, and events as a separate object. This also represents a huge leap forward relative to ADO.
The ADO recordset can define a filter string. Once you have established the character channeling, only data that matches a specific standard can be read and written.
FilterA property works like a dynamic where clause. It simply hides some records on the same Recordset object view.
In ADO, you never have a separate view object. A filtered recordset is always the same object, except that it shows a smaller number of records than it actually is.
It doesn't matter if you don't have to deal with different views at the same time. The programming interface gives the recordset the ability to be either a table or a view. However, this cannot happen at the same time as it is created. At a particular point, the Recordset can only be a table without a filtered string or a view that activates the filtered string.
Cloning of a Recordset provides a better way to resolve this structural constraint. As the clonation and the case of Table Dolly said in Part 1, the clone Recordset is relatively inexpensive because it does not replicate data, but simply copies the basic constructs of the recordset. To process two or more views of the same data, you can use two or more clones, each with a corresponding filter string.
figure I process different views of the same recordset in ADO
In Ado.net, you can use the new object model to provide the
DataViewObject. Ado. NET of
DataViewobject is used to represent a customized view of a given data table, but you can handle it as if you were a separate object.
DataViewObject retains a reference to the table and allows it to be updated.
Figure II Operation of different views of the same datasheet in Ado.net
Functionally, using an ADO recordset clone is the same as using a special view object to enable you to filter, manipulate the selected rows of data, and handle multiple views at the same time.
Deep DataView Objects
The DataView object inherits the MarshalByValueComponent and implements a set of interfaces that are available in the data-bound control. Public Class DataView
Inherits marshalbyvaluecomponent
Implements IBindingList, IList, icollection,ienumerable, _
ITypedList, ISupportInitialize
A class derived from MarshalByValueComponent is a. NET remote component that can be set by value-that is, the serialized object to the target application domain. (see below for more details.) More details of the net component)
The content in DataView can be manipulated through a number of programming interfaces, including collections, lists, and enumerators. The IBindingList interface ensures that the class provides all the necessary features to support complex and simple data binding.
In general, the DataView object can be used to achieve two goals. First, views are important for associating a DataTable object with a DataSource field in a data-bound control. Second, it also provides a layer of packaging for the linked DataTable, allowing you to filter, sort, edit, and browse.
DataView is not the only data-driven class that can be remotely manipulated by passing values. Datasets and DataTable also have the same capabilities, especially in interoperation scenarios.
Create DataViewpublic DataView ();
Public DataView (DataTable);
DataView is only available if it is connected to a DataTable object that already exists, most likely non-null. Typically, this connection is specified at construction time.
DataView DV;
DV = new DataView (thedataset.tables["Employees"]);
However, you can also first create a new view and then associate it with the table property.
DataView dv = new DataView ();
Dv. Table = thedataset.tables["Employees"];
The DataView constructor allows you to get a DataView object from the DataTable. If necessary, the reverse is also true. In fact, the DefaultView property of a DataTable object returns a DataView object for that table.
DataView dv = dt. DefaultView;
Once you have the
DataViewobject, you can use its properties to build the set of data you want the user to see. Generally, you can use the following properties:
The former can customize the rules that the visible data in the view should match. The latter is sorted by an expression. Of course you can use any combination of the two.
Set Filter
RowFilteris a read-write property that is used to read and set the expression for table filtering.
Public virtual string RowFilter {get; set;}
You can use the column name, logical and numeric operators, and the arbitrary combination of constants to form an expression. Here are some examples: DV. RowFilter = "Country = ' USA '";
Dv. RowFilter = "EmployeeID >5 and Birthdate < #1/31/82#"
Dv. RowFilter = "Description like ' *product* '"
Let's take a look at the basic rules and operators for the filter.
A filter string is a logical connection to an expression. You can use And,or,not to connect to a shorter expression, or you can use parentheses to form clauses that specify precedence operations.
A clause that usually contains a column name is compared to a letter, a number, a date, or another column name. Here, you can use relational operators and arithmetic operators, such as >=, ",", +, *,% (modulo), and so on.
If the rows to be selected are not easily expressed by arithmetic or logical operators, you can use the in operator. The following code shows how to select a random row:
Dv. RowFilter = "EmployeeID in (2,4,5)"
You can also use wildcards * and%, which are more useful when used with the LIKE operator. They all represent any number of characters and can be used in lieu of each other.
Note that if you already have a * or a% character in the LIKE clause, you must enclose it in square brackets to avoid ambiguity. If it is unfortunate that the parentheses themselves exist in the string, then it must also be enclosed in itself. In this way, the matching statement looks like this:
Dv. RowFilter = "Description like" [[]*[]]product[[]*[]] "
Wildcard characters are allowed only at the beginning or end of a filter string, not in the middle of a string. For example, the following statement produces a run-time error:
Dv. RowFilter = "Description like ' prod*ct"
The string must be enclosed in single quotes, and the date type must be enclosed in the # symbol. The decimal and scientific notation can be used for character values.
RowFilter also supports aggregate functions, such as SUM, COUNT, Min,max, and AVG. If there are no rows of data in the table, then the function returns NULL.
At the end of introducing the RowFilter expression, let's discuss three very handy functions: len,iif and substring.
As its name, Len () returns the length of a particular expression. The expression can be a column name, or it can be another legitimate expression.
Substring () returns a string of characters subcode a specified length, starting at a specific position.
My favorite use is IIf (), which has a value of one to two according to the value of the logical expression. IIF is a compact expression of if-then-else statements. The syntax is as follows:
IIF (expression, if_true, If_false)
With this function, you can create a very complex filter string. For example, suppose you get the Employees table from the Northwind database of SQL Server, The following expressions can be used to select employees whose EmployeeID is less than 6 and LastName as an even number of characters and EmployeeID is greater than 6 and LastName as odd characters.
IIF (Employeeid<6, Len (lastname)%2 =0, Len (lastname)%2 >0)
The following figure shows the results (the sample application will be discussed later)
figure three filters the tables in Northwind
The example program is a windows®form application that uses two DataGrid
Control to implement the Master/detail structure. A grid is generated when loaded, that is, in the SQL
After the Server data adapter completes the data read work. Please note that the data
The adapter is introduced in Beta 2, and the corresponding Sqldatasetcommand class is in Beta 1. <BR>
Pre-Arrange view
In the example above, the DataGrid must be responsible for the rows of data in the preset view to refresh the user interface. The automatic mechanism is. NET
The product of data binding. The DataGrid is passed
DataSourceproperty to get the data-bound control of the data. DataView is a data-bound class that can build
DataSourceThe contents of the property. <BR>
What should you do if you want to use another control other than the DataGrid? And what if you don't want to use automatic data binding? How do I arrange the selected data rows in the view? <BR>
DataView's
TableProperty points to the appropriate datasheet, but D
atatableFiltering information is not saved. Therefore, the data in the scheduling table is doomed to be infeasible. Although D
atatableAnd
DataVieware closely linked, but they are independent and perform independent functions. <BR>
The following visual Basic. NET code snippet shows how to traverse all the data rows in the view and add them to the listbox.
Dim DV as New DataView ()
DV = ds. Tables ("Employees"). DefaultView
Dv. RowFilter = "EmployeeID >5"
ListBox1.Items.Clear ()
Dim BUF as String
Dim Dr as DataRowView
For all Dr in DV
BUF = ""
BUF &= Dr ("LastName"). ToString () & "," & Dr ("FirstName"). ToString ()
LISTBOX1.ITEMS.ADD (BUF)
Next
As mentioned earlier,
DataViewis an enumerable class, so you can safely pass it to for. Each statement. The Count property stores the number of data rows in the view so that the Next loop.
To access a row in the view, you can use the
DataRowViewClass.
DataRowViewcan be expressed
DataRowThe view, just like
DataViewExpress the same view as the DataTable customization.
In general, DataRow has a maximum of four states: Default,original,current and proposed. These states are represented by the
DataRowVersionEnumeration type settings, which are set by the
rowversionAttribute expression.
A DataRow view can only be one of these states.
The default version of a data row is only available when its columns are set at construction time by default values. The initial (original) version refers to the last invocation of the table's
AcceptChanges, the data rows or snapshots are obtained from the source of several dramas. The current version refers to the current data row, including all updates that occurred at that time. The proposed state exists only in the editing process that calls BeginEdit and EndEdit.
can be accessed by accessing
DataRowThe same syntax access
DataRowView。 The most important property here is called item.
sorting and other convenient features
DataView supports the sort attribute, which you can use to sort the contents of a view. Sort is sorted by a comma-delimited column name expression. By adding ASC or DESC qualifier to any column name, you can make the fields in ascending or descending order. If there is no orientation qualifier, the default order is ASC.
DataView is an in-memory object, so sorting is done locally without invoking the database server.
RowStateFilteris another interesting attribute of DataView. It can filter the contents of the DataTable with any predefined criteria. The following table contains all values for the DataViewRowState enumeration type: CurrentRows includes all updates that are not updated, New and modified data rows deleted all data rows that have been deleted since the last call to AcceptChanges modifiedcurrent all data rows that have been modified since the last call to AcceptChanges modifiedoriginal all since the last call Acceptchange s original version of data row new all the newly added row originalrows after the last call to AcceptChanges returns the initial data row, deleted all of the data rows that contain unchanged and unchanged
If you want to manipulate data that is not connected, all updates are
DataTableCall
AcceptChangesAfter the entry into force. Updates to a single row are called
DataRowOf
AcceptChangesAfter the entry into force. Similarly, these updates can be done by calling the
DataTableOr
DataRowobject's
RejectChangesTo cancel.
DataViewObjects also have properties, such as
Allowedit,allowdeleteAnd
AllowNewTo get or set whether the updated value is allowed. Their default value is set to true, allowing any kind of update. If you want to complete the appropriate update operation when the flag is set to False, a run-time error occurs.
DataViewManager class
DataTableobject's
DefaultViewproperty is used to return a
DataViewObject as the default view of the content in the datasheet. It reads the data in a natural order and displays all the rows in the table without using any filtering.
Themastergrid.datasource = M_ds. Tables ("Employees"). DefaultView
If you need a data-specific view, you can sort and/or filter the DefaultView object directly.
M_ds. Tables ("Employees"). Defaultview.sort = "LastName"
Themastergrid.datasource = M_ds. Tables ("Employees"). The Defaultviewdataviewmanager class is used to store view settings for all tables in the dataset.
You can create a DataViewManager by passing a valid Non-empty dataset to the constructor of the class
Dim DVM as DataViewManager
DVM = New DataViewManager (m_ds)
It can also be obtained directly from the Defaultviewmanager property of the DataSet object:
Dim DVM as DataViewManager = M_ds. Defaultviewmanager
It is important that the DataViewManager class is associated with a dataset. Here's another possible way to do this:
Dim DVM as New DataViewManager ()
Dvm. DataSet = M_ds
The most important attribute of DataViewManager is Dataviewsettings, a collection of DataViewSetting objects.
Dim DVS as DataViewSetting
DVS = DVM. Dataviewsettings ("Employees")
Dvs. Sort = "LastName"
dataviewsettingobject contains parameter information for the table view. When binding data to data-sensitive controls, you can preserve your view settings (filter and Sort fields) using DataViewManager instead of a dataset or DataTable.
Themastergrid.datasource = DVM
Themastergrid.datamember = "Employees"
Here, the view is sorted and filtered automatically according to the Employees table specified in DataViewSetting. In other words, the DataViewSetting class is a cache of views on a particular table.
Next
The above example program uses the filter to realize the MASTER/DETAIL structure. If you use. NET, the data-bound control (such as the DataGrid) is better to achieve this goal. In a future column, I'll discuss the data relationships in memory and how they affect the design of the master/detail structure.
dialog: Do you need controls or components?
There are many terms in. NET that can often be used instead. The special points here are: classes, components, objects, and controls. Here, I provide a table that describes the proper meaning of each term. We often use them as synonyms.
What needs to be kept in mind is the whole. NET schemas are made up of classes. So whatever you get from it, first of all, is a class. In a. NET environment, controls and components are not of the same kind. As for the object, it can be thought to be running. The instance of the net class.
A component is a special class that implements a IComponent interface or a class that derives from the IComponent interface.
A control is a component that provides user interface functionality. In the. NET architecture, you can find two types of controls: The client's Windows Forms control and the ASP.net server control.
The IComponent interface is contained in the IDisposable interface and provides a determined way to purge resources.
Public Interface IComponent
Inherits IDisposable
This method of releasing resources and the standard. NET garbage collector can choose one of the two. By implementing IDisposable, you define a Dispose method. By programming, you can explicitly release the object without waiting for the garbage collector to process it.
. NET component knows how to concatenate in application domains (application domain). There are two ways to do this: by referencing or passing values, the basic functionality is built into the marshalbyrefcomponet and MarshalByValueComponent classes respectively.. NET component class, in fact, implements the IDisposable, However, one of the above two classes is inherited directly or indirectly.
An application domain is a lightweight process. The column set object by reference means that the Proxy/stub entity pair is created and the remote invocation is processed. By value means that the serialized copy of the object passes across the bounds of the domain.
Control is a more specialized object, and it also provides user interface elements. Of course, a control is always a component, but the opposite is not necessarily true.