Some easily confusing concepts in DataTable, DataView and DataGrid

xiaoxiao2021-03-06  20

First, DataTable DataTable indicates a table in the memory, which is completely independent in memory, which contains all the information of this table. DataTable can be from a table that is formed from the database through the connection, once this DataTable can be opened independently with the data source, it can also be created by the programself by the program. A table. ◆ The Datacolumn is a two-dimensional structure consisting of rows and columns. The structure of the table is composed of a collection of DataColumn objects. The DataColumn object collection can be obtained from the DataTable.Columns property that determines the schema in the table by defining the data type of each column. Defining the structure of the table can generate DATAROW according to the structure, use the DataTable.newrow () method to generate a new line of this DataTable structure. A DATATABLE is composed of DataRow's collection, and the collection of DataRow can be accessed by the DataTable.Rows property. DataTable can also create some columns through expressions with existing Expression properties. 1. Create a calculated column such as: There is a table structure, there is a collection of Datacolumn in the table, with a column called Unitprice, you can create a new Datacolumn, set the columnName, set this column, Datacolumn.expression = "UnitPrice * 0.086", the value of this column is calculated by column for Unitprice. When creating an expression, use a columnName property to reference columns. 2, the second use is to create a polymerization column aggregation usually along the relationship (see the DataRelation section below related to the relationship), if the ORDER table is known as the subtaby table named Detail, two tables pass ORDER. ORDERID and DETAIL Two columns to establish a relationship DataRelation object name "Order2Detail", you can create a gale column in the primary table ORDER, calculate the price of all Items included in the Detail table: Datacolumn.Expression = "SUM (Order2Detail)", Child (ORDER2DETAIL) represents the child table that is linked by the relational order2detail, and Child (ORDER2DETAIL) .price represents the PRICE column of the sub-table. ◆ The DataRowDataRow object does not use the constructor used in the code, which is generally created from the newrow () method from the newrow () method from a DATATABLE with a certain structure. A DATAROW is different from whether it is independent or a DATATABLE, whether it is modified, whether it is different from DataTable deletion, etc., is disclosed by the DATAROW.ROWSTATE attribute, as shown in the following table:

Member name

Description

Added The row has been added to DataRowCollection, and AcceptChanges has not been called. DELETED This line has been deleted through the DELETE method of DATAROW. DELETED This line has been deleted through the DELETE method of DATAROW. Detached This line has been created, but does not belong to any DataRowCollection. DataRow is immediately in this case: Before being created, it is added to the collection; or remove it from the collection. Modified has been modified, and AcceptChanges has not been called. Unchanged This line has not changed since the last call AcceptChanges. A DATAROW object is just created, its status is detached, is an isolated one existence, so after the DataRow is created, the data is filled with the data in DataRow and add this DataRow to DataTable. After DATAROW is added to DataTable, the status of this DATAROW is converted to Added. When this DATAROW is modified, this DATAROW status is converted to modified. When DataRow.delete () method is deleted, the DATAROW status will be turned to deleted, but this line still exists in the DataTable, but the state changes, at this time Use DataTable.Rows.count to view the number of rows, before the deletion is the same. This DATAROW is only removed from the DataTable and the status is also removed from the DataTable.Remove (DataRow) method. Once the DataTable.AcceptChanges () method is called, all rows will do different processing, add, modified, unchange according to different states, and the DELETED's line will be removed from the DataTable, and the status of all rows are set. To unchanged. When DataTable is formed from a DataAdapter.Fill (DataSet, DataTable) method, the Fill () method will automatically call the AcceptChanges () method, set the DataTable's row status to unchanged. And, if the DataTable specified in the Fill method does not exist when the Dataset to be filled, a DataTable with the same structure as the data source table is generated and populated. ◆ DataRelation represents the parent / sub-relation between the two DataTable objects. You can class more than the relationship between the tables in the database, the parent table is equivalent to the table that is the primary key, and the sub-table is equivalent to the table of the foreign key. The Dataralation constructor is generally: Dataralation (String, Datacolumn, Datacolumn), String is a relationship name, the first Datacolumn is the parent table column of the establishment of a relationship, the second Datacolumn is the two columns of the establishment of a relationship, two columns The DATATYPE value must be the same. It has been established, and this relationship must be added to the DataTable ParentRelations property or the childrelations property, which contains all the relationships of this table and the relationship of the follower table. If this table is a parent table, this relationship is added to the Childrelations collection, otherwise join the ParentRelations collection.

Second, DataViewDataView represents custom views for DataTable for sorting, filtering, searching, editing, and navigation. DataView can be used with the database of the database, but the database's view can create views across tables, and DataView can only create views for a DataTable. DataView generally creates a subset of this DataTable by using the DataTable.defaultView property. The RowFilter property is used to filter the expressions to see which rows in DataTable, which is the same as the expression of the columns above. For example: "LastName = 'Smith'", this is the data line that only views the value of the column LastName is 'Smith'. The ROWSTATEFILTER property is used to set the row status filter in the DataView. When you introduce DataRow, you will have five states, a DATAROW may have five states, and RowStateFilter is to filter the rows you want to view through these states. In fact, DATAROW is not only five states, but also has version problems, such as the status of DATAROW is modified, that is, this line has been modified. At this time, this DataRow will have two versions, Current version and Original version (before modifying of). In fact, the ROWSTATEFILTER attribute is to filter status and version of DataRow (RowStateFilter's value is currentrow) See below: Member Name

Description

ADDED a new line. Currentrows includes current rows that have not been changed, new row, and modified rows. DELETED has been deleted. ModifiedCurrent Current Version, Original Data (see Modifiedoriginal) modified version. Modifiedoriginal Original version (although it has been modified and exists in modifiedcurrent). None none. OriginalRows includes raw rows that have not been changed and deleted. Unchanged has not changed. The count obtained by the DataView.count property is to get the number of records recorded in the DataView after applying RowFilter and RowStateFilter. DataView is based on DataTable, and the dataview.table property can get the DataTable corresponding to this DataView. DataView's row is called DataRowView, you can get this DataRowView corresponding to DataRowView from DataRowView.Row property. Third, DataGrid said that DataGrid is the DataGrid in WinForm, generally with DataView binding to display data in DataTable, and modify data in the DataTable. DotNet's DataGrid is powerful, but in use, it is not too kind. Sometimes it is more troublesome, so many people feel that some people feel some of them can't touch the mind, there is a feeling of unlikely, it is actually clear some concepts. Many problems will be solved. DataGrid Binds the data source to be displayed through the DataSource and DataMember properties. Data sources are generally DataTable, DataView, DataSet, etc., but the data source is bound to DataGrid is actually binding DataView. If the data source is DATATABLE, it is actually a defaultView that is bound to this DataTable. If the data source is DataSet, you can set a string to the DataMber property, which specifies the table to be bound, and then DataMember The specified DATATABLE DEFAULTVIEW is bound to the DataGrid. So DataGrid actually displays DataTable's screening DataView. ◆ DataGrid What way to display DataView's Data DataGrid Bind to a DataView, the collection of DataGridTableStyle objects in DataGrid.TableStyles, which is displayed, how much is the width of the column, what is the text of the column header? and many more. Individual data does not contain any objects in DataGrid.TableStyles, and the DataGrid will appear all columns in the order of the DataView column. TableStyles will be set in general applications to control the contents and formats displayed. For example, DataGrid is bound to a DataTable called Order. This DataTable contains fields such as ORDERID, Customerid, ORDERDATE, SHIPNAME, SHIPADDRESS. If you do not need toStyles to control the displayed columns and format, you will get the following display results: Figure-1 can Seeing DataGrid will display all columns in the order of the DataView column we just want to display the three fields of ORDERID, CUSTOMERID, ORDERDATE, and want to display the list of ORDERID as "Order Number", Customerid is displayed as "customer No. ", ORDERDATE is displayed as" order date ", which is to be controlled with tablestyles.

Create a TableStyle, this corresponds to the name of the attribute TableStyle.MappingName DataTable this TableStyle to be controlled: DataGridTableStyle myTableStyle = new DataGridTableStyle (); myTableStyle.MappingName = "myDateTable"; then create three DataGridColumnStyle, respectively, to be displayed to control Three columns:

DataGridColumnStyle myColumnStyle1 = new DataGridTextBoxColumn (); myColumnStyle1.MappingName = "OrderID"; myColumnStyle1.HeaderText = "Order Number"; DataGridColumnStyle myColumnStyle2 = new DataGridTextBoxColumn (); myColumnStyle2.MappingName = "CustomerID"; myColumnStyle2.HeaderText = "customer number"; DataGridColumnStyle myColumnStyle3 = new DataGridTextBoxColumn (); myColumnStyle3.MappingName = "OrderDate"; myColumnStyle3.HeaderText = "Order date"; these three DataGridColumnStyle added to TableStyle in:

myTableStyle.GridColumnStyles.Add (myColumnStyle1); myTableStyle.GridColumnStyles.Add (myColumnStyle2); myTableStyle.GridColumnStyles.Add (myColumnStyle3); TableStyle finally added to the DataGrid:

DataGrid1.tables.Add (MyTableStyle); After adding tableStyle to DataGrid, then bind the data source, then we will see such data: Figure-2 ◆ DataGrid editing DataGrid support to DataGrid DataTable editing modification, as long as the DataGrid's readOONLY property is false, you can directly modify the contents in the DataGrid. After modifying the data, the data will directly react directly to the DataTable unit corresponding to this DataGrid. If this DataTable is newly built DataAdapter through VS.NET, and generates SELECTCOMMAND, INSERTCOMMAND, UPDATECOMMAND, DeleteCommand, with DataAdapter's Fill method, then things is simple, modified DataTable You can write back to the database with DataAdapter's Update method. Let's take a look at the INSERTCOMMAND command generated by VS.NET's visual data.

this.sqlInsertCommand1.CommandText = @ "INSERT INTO Customers (CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax) VALUES (@CustomerID, @CompanyName, @ContactName, @ContactTitle, @Address , @City, @Region, @PostalCode, @Country, @Phone, @Fax); SELECT CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax FROM Customers WHERE (CustomerID = @CustomerID ) "; this.sqlInsertCommand1.Connection = this.sqlConnection2; this.sqlInsertCommand1.Parameters.Add (new System.Data.SqlClient.SqlParameter (" @ CustomerID ", System.Data.SqlDbType.NVarChar, 5," CustomerID ")) ; this.sqlInsertCommand1.Parameters.Add (new System.Data.SqlClient.SqlParameter ( "@ CompanyName", System.Data.SqlDbType.NVarChar, 40, "CompanyName")); this.sqlInsertCommand1.Parameters.Add (new System. Data.Sqlclient.sqlparameter ("@ contactname", system.data.sqldbtype.nvarchar, 30, "contactname"); this.sqlinsertcommand1.parameters.add (New System.dat) a.SqlClient.SqlParameter ( "@ ContactTitle", System.Data.SqlDbType.NVarChar, 30, "ContactTitle")); this.sqlInsertCommand1.Parameters.Add (new System.Data.SqlClient.SqlParameter ( "@ Address", System .Data.sqldbtype.nvarchar, 60, "address"); this.sqlinsertcommand1.parameters.add (new system.data.sqlclient.sqlparameter ("@ city", system.data.sqldbtype.nvarchar, 15, "city" )); this.sqlinsertcommand1.parameters.add (new system.data.sqlclient.sqlparameter ("@ region", system.data.sqldbtype.nvarchar, 15, "region"));

this.sqlInsertCommand1.Parameters.Add (new System.Data.SqlClient.SqlParameter ( "@ PostalCode", System.Data.SqlDbType.NVarChar, 10, "PostalCode")); this.sqlInsertCommand1.Parameters.Add (new System.Data .SqlClient.SqlParameter ( "@ Country", System.Data.SqlDbType.NVarChar, 15, "Country")); this.sqlInsertCommand1.Parameters.Add (new System.Data.SqlClient.SqlParameter ( "@ Phone", System. Data.sqldbtype.nvarchar, 24, "phone"); this.sqlinsertcommand1.parameters.add (new system.data.sqlclient.sqlparameter ("@ fax", system.data.sqldbtype.nvarchar, 24, "fax") ); DataAdapter SELECTCOMMAND is used to fill DataAdapter.Fill () methods, and the data table line set selected by SelectCommand will be populated into the DataTable, then DataGrid is displayed. DataGrid After editing, the five states in the corresponding DataTable may have the five states described above, probably, may be modified, may be deleted ( DetaAdapter.Update () method will insert the status of the statue to the database by calling the insertCommand command, updateCommand will modify the state of the model MODIFIED in the database, and DeleteCommand will state the state of the DELETED truly delete. If you don't create a DataAdapter from VS.NET, you may need to automatically generate SELECTCOMMAND, INSERTCOMMAND, and you may need to write InsertCommand, updateCommand, deleteCommand command yourself, there is a situation to return at least when SELECTCOMMAN When a primary key list or unique column, you can generate another three update commands from the SQLCommandbuilder from the selectcommand command, for example:

SqlConnection myConn = new SqlConnection (myConnection); SqlDataAdapter myDataAdapter = new SqlDataAdapter (); myDataAdapter.SelectCommand = new SqlCommand (mySelectQuery, myConn); // establish the DataAdapter SelectCommand command SqlCommandBuilder custCB = new SqlCommandBuilder (myDataAdapter); // create this DataAdapter CommandBuilder, // This system will automatically generate three commands for this DataAdapter to generate INSERTCOMMAND, UPDATECMMAND, and DeleteCommand. Otherwise, use the DataAdapter.Update () method to update the database to write INSERTCOMMAND, UPDATECOMMAND, DELETECOMMAND three commands, you can refer to the write method of the INSERTCOMMAND command that is given above. ◆ Many controls in the Synchronization of Data Binding WinForm can be bound to the data source, binding, two cases: simple data binding simple data binding refers to binding a control to a single data element (such as data set tables) The value of the value in the column). This is a typical binding type for controls, such as TextBox controls, or Label controls (ie, only controls that only display a single value). In fact, any properties on the control can be bound to fields in the database. Complex data binding complex data binding refers to the ability to bind a control to multiple data elements, typically bind to multiple records in the database, or bind to multiple any other type of bonded data element, general Is binding to a DataView. Examples of support for complex binding controls include DataGrid, Listbox, and ErrorProvider controls. General DataGrid controls are binded to a DataView, DataGrid's data bindings are complex bindings because it binds to tables with multiple records, and DataGrid has two attributes related to data binding: DataGrid.DataSource Properties: Get Or set the data source of data displayed in DataGrid. It is generally binding to DataTable, DataView, DataSet, if the DataSource is set to DataSet, then the included table is not only one, then you must set a string to the DataMber property, which specifies the table to be bound. DataGrid.Datamember Properties: Get or set a specific list in DataSource, which is the above DataSource to set this property to specify the table to be bound. There is often this requirement, there is a DataGrid in a form, showing some data, and some TextBox controls on the form, which uses data in the DataGrid, a TextBox control corresponding to a column of the DataGrid line, When the current row of DataGrid moves, the value in the TextBox control will also follow the current row of the DataGrid that changes the change. To ensure that these data binding controls keep synchronization, you must have a unified management data binding mechanism to ensure synchronization of these controls. The data synchronization is bindingmanagerbase in the DOTNET, which is used to manage data sources, bind to the same data. The source data binding control can be managed by BindingManagerBase. BindingManagerBase can be obtained by form.bindingcontext.Item property, this property has two overloads:

public BindingManagerBase this [object DataSource] // get associated with the specified data source BindingManagerBasepublic BindingManagerBase this [object DataSource, string DataMember] // data source to obtain a BindingManagerBase the specified data source and data associated with members of all data-bound controls establishing the same object passed as BindingManagerBase, will belong to this BindingManagerBase management, for example, following the establishment of a BindingManagerBase: BindingManagerBase myBindingManagerBaseParent = this.BindingContext [myDataSet, "customers"]; if there DataGrid on Form DataGrid.DataSource = MyDataSet; DataGrid.DataMember = "Customers", then this DataGrid's data source is under myBindingManagerBaseParent management. The same simple data binding control is also the same as the DataSource of BindingManagerBase. When DataMember is a list of the table specified by BindingManagerBase, the data source of this control is also under this MyBindingManagerBaseParent management:

dataGrid1.DataSource = myDataSet; dataGrid1.DataMember = "customers"; textCustomerId.DataBindings.Add (new Binding ( "Text", myDataSet, "customers.customerid")); // TextBox Text property with customers table // myDataSet Customerid field Binds BindingManagerBase control's data source has a current line concept, once the control is bound to the data source, DataGrid will display all data of the data source table, but there is a black triangle arrow in the DataGrid header Used to indicate the current line. The value displayed in the simple binding control will be the content of the current line of the data source. So, as long as we change the BindingManagerBase's pointer, this can change the current row by clicking on the line you want, or change the current line settings in the program:

MyBindingManagerBaseParent.position = 10; BindingManagerBase.Position Attribute changes will cause changes in BindingManagerBase the current row, that is, the current line of DataGrid binding this data source, the display content of simple binding controls will change. ,As shown below.

Figures-3 The current line is the first line, the three TEXTBOX controls above also display the data of the first line.

Figure 4, the three TEXTBOX controls are also displayed on the fourth line of data.

BindingManagerBase's DataSource can be a DataSet, which can have multiple DataTable in DataSet, which can be associated with DataRelaton (relationship) to form the relationship between the parent table / subtaby. For example, still the example mentioned above, a DataGrid displays the Customer table, but also wants to have a DataGrid to display all of the current Customer all ORDER. This way we will need two BindingManagerBase, a BindingManagerBase corresponds to the Customer table, and the other BindingManagerBase corresponds to the Order table, and this Order Table also considers the relationship with the Customer table. Corresponding to Customer's BindingManagerBase has been established, let's establish a BindingManagerBase corresponding to Order: First we have to build the relationship between the Customer Table and the Order Table MyRelation: Datacolumn ParentColumn = MyDataSet.Tables ["Customers"]. Columns [" Customerid "]; // To establish a column of the parent table of the relationship, equivalent to the primary key Datacolumn ChildColumn = myDataSet.tables [" Orders "]. Column [" Customerid "]; // To establish a column of the relationship, equivalent Foreign key DataRelation MyRelation = New DataRelation ("MyRelation", false, childcolumn, false); // establishes a relationship according to the related column of the child table, then establishing a BindingManagerBase corresponding to the Order table by relationship.

MybindingManagerBasechild = this.bindingContext [myDataSet, "CUSTOMERS.MYRELATION"]; // This data source will resolve all ORDER corresponding to the customer in a parent table, when the current row of Customer's BindingManagerBase is changed, corresponds to Order BindingManagerBase will also follow, the relationship between them is determined by MyRelation, as shown below:

Figure-5

The DataGrid of the corresponding sub-table ORDER displays all of the ORDER of the Alfki client in the parent table, when clicked in the "Master Table" button, the current customer in the parent table changes to anaTr, the child table also changes to the display corresponding ANATR All ORDER

◆ Visit the contents of DataGrid in the program DataTable DataRow, and there is no such thing in the DataGrid, which makes people feel very uncomfortable, and it feels not natural. In DataTable, the hierarchy of a table is clear, the DataTable.Rows property can get the rowset of all rows contained in this table, and you can get a specific DataRow, data line by the index of the row. Index DATAROW [INDEX] can also get the specific column of this line. It is not so convenient in DataGrid. DataGrid is only available, the dataGrid.currentcell property, this property returns a structure of a DataGridcell type, and the DataGridcell structure indicates the line number and column number of this Cell. There is also a DataGrid.Item property, this property has two overload: public object this [dataGridcell] // Get or set the value of the specified DataGridcell PUBLIC OBJECT THIS [INT] // Get or set to be specified and columns The value of the cell is visible, and the access to the DataGrid is performed for a CELL. Often, we need to get the DataRow corresponding to this Cell from the current Cell, such as the interface you may select first, or a Cell, then click on a button, pop up a new window, show this line in the window. The content of all units, and allows the value of the unit to last, and finally the shutdown window is saved. This requires the lines and columns of the DataTable corresponding to the unit where the current DataGrid is located. The data displayed in the DataGrid may pass through the DataView's DataView.rowfilter property, the data of the DataView.RowStateFilter property, may also pass through the DataGrid itself according to the forward and reverse sorting of each column, so the row index indicated by the DataGrid's CURRENTROWINDEX attribute The corresponding DataTable row is a big chance to be different, and it is not possible to get the corresponding DataTable row according to the DataGrid's currentrowindex. At this time, BindingManagerBase will work, we can build a BindingManagerBase that corresponds to the data source bound to this DataGrid, so this BindingManagerBase can manage this data source.

// Set DataGrid data source dataGrid1.DataSource = myDataSet; dataGrid1.DataMember = "customers"; // build BindingManagerBaseBindingManagerBase myBindingManagerBaseParent DataGrid with the same data source = this.BindingContext [myDataSet, "customers"]; Once this BindingManagerBase, You can get a record of the current data source through the properties of BindingManagerBase's current row:

// bindingManagerBase's Current Returns the object of the data source, for the data source bound to the DataView, you need to explicit // of this object to DataRowView Type DataRowView myDatarowView = (DataRowView) MybindingManagerBaseParent.current This, we can come from current Cell gets this Cell's DataRowView, DataRowView can also get DATAROW through the DATAROWVIEW.ROW attribute and its convenience. If necessary, if you want to get the specific unit of the DataTable corresponding to this Cell, it is not only to get DataRow, and you have to know the column corresponding to this Cell. This is divided into two situations: First, DataGrid does not use tableStyles to set the column and format to display, and all columns of data source DataView will be displayed in the order of DataView itself, which can directly obtain the corresponding column index: // Get the column index of the current DataGrid unit, this index is the same int columnNumber = dataGrid.currentcell.columnNumber; another situation is that DataGrid uses TableStyles to set the column and format to display by DataGrid, so that the column of the DataGrid unit Indexing with the index of DataTable may be different, this is going to use DataGrid's TableStyles:

Int ColumnNumberDataGrid = DataGrid.CurrentCell.ColumnNumber; // get the current column index DataGrid unit Int ColumnNumberDataTable = DataGrid.TableStyles [0] .GridColumnStyles [ColumnNumberDataGrid] .MappingName

Author Blog:

http://blog.9cbs.net/chnking/

related articles

Document Upload and Download ASP.NET How to trigger the VS.NET Web Project to use Visual Source Safe to manage Table's width, cells in units, wirelines, use the client script, used control name problem

Comments on this article

INELM (2005-02-17) Very Good Article.

WF21CN (2004-12-23) strong !! But always feel DataGrid after the binding, can only modify the current Cell value each time, it is very unhappy! That is, to set the target cell into the current Cell, can you find it Current Cell's DataRow is modified. When the amount of data is large, the speed is slow ..

9CBS netizen (2004-08-28) is very good, can you provide source code?

Builderman (2004-05-22) Master helps to see this code, the result to get is: After selecting DataGrid1, DataGrid2 in DataGrid2 will filter DataSet DS = New DataSet (); DS = SQLHELPER.EXECUtedataset Constring, CommandType.text, "SELECT * from STK_IN; SELECT * from" STK_IN_DTL "); DS.TABLES [0] .tablename =" STK_IN "; DS.TABLES [1] .tablename =" STK_IN_DTL "; DATACOLUMN PARENTCOL = DS. . Tables [ "stk_in"] Columns [ "stk_in_no"];. DataColumn ChildCol = ds.Tables [ "stk_in_dtl"] Columns [ "stk_in_no"]; DataRelation myRelation = new DataRelation ( "myRelation", ParentCol, ChildCol, false); ds.Relations.Add (myRelation); dataGrid1.SetDataBinding (ds, "stk_in"); dataGrid2.SetDataBinding (ds, "stk_in_dtl"); BindingManagerBase bmbParent = this.BindingContext [ds, "stk_in"]; BindingManagerBase bmbChild = this. BindingContext [DS, "STK_IN.MYRELATION"]; WANGGANG99 (2004-04-21) This DataTable can be independently existed with the data source; it can also be a table created by the programself by code. If the DataTable at this time has 100 million data, don't die.

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

New Post(0)