What Is a DataView Object?

DataView Object Reference

Properties of the DataView Object

In Table 8-2 you'll find all the properties of the DataView object.

Table 8-2 Properties of the DataView Object

Property

Data Type

Description

AllowDelete

Boolean

Specifies whether rows in the DataView can be deleted.

AllowEdit

Boolean

Specifies whether rows in the DataView can be edited.

AllowNew

Boolean

Specifies whether rows can be added to the DataView.

ApplyDefaultSort

Boolean

Specifies whether the default sort (primary key) is used.

Count

Integer

Returns the number of rows visible in the DataView. (Read-only.)

DataViewManager

DataViewManager

Returns a reference to the DataView object's DataViewManager. (Read-only.)

Item

DataRowView

Returns a DataRowView that encapsulates a row of data visible through the DataView. (Read-only.)

RowFilter

String

Contains a filter that specifies which rows in the DataTable are visible through the DataView. Similar to the WHERE clause in a SQL query.

RowStateFilter

DataViewRowState

Specifies what rows can be visible through the DataView as well as the version of the rows.

Sort

String

Specifies the sort order of the rows visible through the DataView.

Table

DataTable

Returns the corresponding DataTable to which the DataView is bound.

AllowDelete, AllowEdit, and AllowNew Properties

DataView objects are often used in conjunction with bound controls. The AllowDelete, AllowEdit, and AllowNew properties simplify the process of restricting the types of changes that the user can make using the bound controls. Rather than setting properties on each of the bound controls, you can set these properties on just the DataView.

By default, each of these properties is set to True on the DataView object.

ApplyDefaultSort Property

The ApplyDefaultSort property is set to False by default. Setting it to True will sort the contents of the DataView according to the primary key of the DataView object's DataTable. If you set ApplyDefaultSort to True, the DataView object's Sort property will be set to the columns in the DataTable object's primary key. For example, if a DataView is bound to a DataTable that contains order detail information and whose primary key is the combination of the OrderID and ProductID columns, setting ApplyDefaultSort to True will implicitly set the Sort property of the DataView to OrderID, ProductID.

Count and Item Properties

The Item property returns a DataRowView object and is parameterized. When you call the Item property, you supply an integer that represents the row you want to retrieve. You can use the Count property to specify the number of rows visible through the DataView. The following code snippet loops through the contents of the DataView by using the Count and Item properties:

Visual Basic .NET

Dim tbl As New DataTable("Customers") 'Retrieve data into the DataTable, and modify some rows.  'Create a DataView that contains only modified rows 'and returns the original contents of those rows. Dim vue As DataView vue = New DataView(tbl) Dim row As DataRowView 'Use a simple For loop to examine the contents of the DataView. Dim intCounter As Integer For intCounter = 0 To vue.Count - 1     row = vue(intCounter)     Console.WriteLine(row("CompanyName")) Next intCounter

Visual C# .NET

DataTable tbl = new DataTable("Customers"); //Retrieve data into the DataTable, and modify some rows.  //Create a DataView that contains only modified rows //and returns the original contents of those rows. DataView vue; vue = new DataView(tbl); DataRowView row; //Use a simple for loop to examine the contents of the DataView. for (int intCounter = 0; intCounter < vue.Count; intCounter++) {     row = vue[intCounter];     Console.WriteLine(row["CompanyName"]); }

DataViewManager Property

If you created your DataView using the CreateDataView method of an instance of a DataViewManager object, the DataViewManager property will return the DataViewManager object that created the DataView. Otherwise, the property will return an uninitialized DataViewManager.

For more information on the DataViewManager object, see the section titled "Questions That Should Be Asked More Frequently" later in the chapter.

RowFilter Property

The RowFilter property is similar to a WHERE clause in a SQL query. Only rows that satisfy the criteria in the property are visible through the view. The default for the RowFilter property is an empty string.

Simple filter that uses a column containing strings:

vue.RowFilter = "Country = 'Spain'"

Filter that uses a wildcard (displaying only rows whose CustomerID starts with A):

vue.RowFilter = "CustomerID LIKE 'A%'"

Delimiting dates:

vue.RowFilter = "OrderDate >= #01/01/2002# AND OrderDate < #02/01/2002#"

Delimiting the column name and handling the delimiter in the column value:

vue.RowFilter = "[Spaces In Column Name] = 'O''Malley'"

RowStateFilter Property

The RowStateFilter property affects the data visible through a DataView in two ways. It filters rows based on their RowState,and it controls the version of the row that's visible through the DataView. The RowStateFilter property accepts values and combinations of values from the DataViewRowState enumeration, as described earlier in the chapter.

You can set the RowStateFilter property using the DataView object's constructor. The default value for the RowStateFilter property is CurrentRows, which causes the view to display the current version of all rows in the DataTable that satisfy the criteria specified in the DataView object's Sort property and are not marked as deleted.

Sort Property

The Sort property controls the sort order of data visible in the DataView; it works much like the ORDER BY clause in a SQL query. You can create a sort order based on a single column or a combination of columns. By default, the rows are sorted in ascending order. To sort columns in descending order, you add the keyword DESC after the column name. Remember to delimit your column name if it contains a nonalphanumeric character (such as a space) or if the column name is a reserved word.

Simple sort by two columns (Country and then City):

vue.Sort = "Country, City"

Sorting in descending order:

vue.Sort = "OrderDate DESC"

Delimiting the column name:

vue.Sort = "[Space In ColumnName]"

By default, the Sort property is set to an empty string, which will display the contents of the DataView in the same order that they appear in the underlying DataTable. You can set this property using the DataView object's constructor.

Table Property

You use the DataView object's Table property to set or access the DataTable to which the DataView is bound. Changing the value of the Table property resets the RowFilter and RowStateFilter properties of the DataView to their respective default values.

You can also set the Table property using the DataView object's constructors.

As of this writing, setting the Table property to a DataTable whose TableName property is an empty string generates an exception.

Methods of the DataView Object

Table 8-3 lists the methods of the DataView object.

Table 8-3 Methods of the DataView Object

Method

Description

AddNew

Creates a new DataRowView object

BeginInit

Temporarily caches changes to the DataView object

CopyTo

Copies DataRowView objects to an array

Delete

Marks a DataRowView as deleted

EndInit

Commits cached changes to the DataView object

Find

Searches the DataView for a row of data

FindRows

Searches the DataView for multiple rows of data

GetEnumerator

Returns an IEnumerator object to enumerate through the rows visible through the DataView

AddNew and Delete Methods

You can use the AddNew and Delete methods to add rows of data to and remove rows of data from the underlying DataTable. The AddNew method returns a new DataRowView object. Once you've set the values of the desired columns, you can call the DataRowView object's EndEdit method to add the row of data to the underlying DataTable.

You can use the Delete method to delete a row if you know the index of the row within the DataView. If you have a reference to the DataRow or the DataRowView, you can call the Delete method of the DataRow or DataRowView object instead. Remember that using the Delete method of any of these objects simply marks the row as deleted. To remove the row from the DataTable, you call the AcceptChanges method (of the DataRow or of the DataTable or DataSet that contains the row) or submit the change to your database using a DataAdapter.

BeginInit and EndInit Methods

If you want to change multiple properties of the DataView object but don't want the changes to affect the data visible through the DataView until you've changed all of the desired properties, you can use the BeginInit and EndInit methods.

For example, say you have a DataView bound to a particular DataTable and you've also set the DataView object's RowFilter property so that only a small fraction of the rows are visible through the DataView. You're displaying the contents of the DataView on a Windows form using a DataGrid, and based on input from the user you want to change the settings of the DataView object's Table and RowFilter properties. In this situation, you should enclose the code that changes the DataView object's properties within calls to the DataView object's BeginInit and EndInit property to prevent the DataGrid from momentarily displaying all rows from the new DataTable.

CopyTo Method

The DataView object exposes a CopyTo method that behaves like the CopyTo method of the Array object. You can copy the DataRowView objects available through the DataView to an array using the CopyTo method.

note

Developers who have experience using DAO, RDO, and ADO might assume that the CopyTo method behaves like GetRows, which returns the contents of the data structure as a two-dimensional array. Alas, this is not the case.

To be honest, I'm not sure how having an array of DataRowView objects helps. However, let's look at a code snippet that demonstrates using this method, on the off chance that someone will find a groundbreaking use for the feature. That person might remember how helpful this code snippet was and thank me profusely. I also accept cash.

Visual Basic .NET

Dim tbl As New DataTable("Customers")  Dim vue As DataView vue = New DataView(tbl) Dim aRows As DataRowView() aRows = Array.CreateInstance(GetType(DataRowView), vue.Count) vue.CopyTo(aRows, 0)

Visual C# .NET

DataTable tbl = new DataTable("Customers");  DataView vue; vue = new DataView(tbl); DataRowView[] aRows; aRows = Array.CreateInstance(typeof(DataRowView), vue.Count); vue.CopyTo(aRows, 0);

Find and FindRows Methods

The DataView allows you to locate one or more rows of data using its Find and FindRows methods. Both methods are overloaded to accept a single value or an array of values. The DataView uses the values specified to search its contents based on the columns specified in the Sort property, as shown here:

Visual Basic .NET

Dim strConn As String = "Provider=SQLOLEDB;Data Source=(local)\NetSDK;" & _                          "Initial Catalog=Northwind;Trusted_Connection=Yes;" Dim strSQL As String = "SELECT CustomerID, CompanyName, ContactName, " & _                        "Phone, City, Country FROM Customers" Dim da As New OleDbDataAdapter(strSQL, strConn) Dim tbl As New DataTable("Customers") da.Fill(tbl) Dim vue As New DataView(tbl) Console.WriteLine("Use the Find method to locate a row " & _                   "based on the ContactName column") vue.Sort = "ContactName" Dim intIndex As Integer = vue.Find("Fran Wilson") If intIndex = -1 Then     Console.WriteLine(vbTab & "Row not found!") Else     Console.WriteLine(vbTab & vue(intIndex)("CompanyName")) End If Console.WriteLine() Console.WriteLine("Use the FindRows method to locate rows " & _                   "based on the Country column") vue.Sort = "Country" Dim aRows As DataRowView() = vue.FindRows("Spain") If aRows.Length = 0 Then     Console.WriteLine(vbTab & "No rows found!") Else     Dim row As DataRowView     For Each row In aRows         Console.WriteLine(vbTab & row("City"))     Next row End If

Visual C# .NET

string strConn = "Provider=SQLOLEDB;Data Source=(local)\\NetSDK;" +                   "Initial Catalog=Northwind;Trusted_Connection=Yes;"; string strSQL = "SELECT CustomerID, CompanyName, ContactName, " +                 "Phone, City, Country FROM Customers"; OleDbDataAdapter da = new OleDbDataAdapter(strSQL, strConn); DataTable tbl = new DataTable("Customers"); da.Fill(tbl); DataView vue = new DataView(tbl); Console.WriteLine("Use the Find method to locate a row " +                   "based on the ContactName column"); vue.Sort = "ContactName"; int intIndex = vue.Find("Fran Wilson"); if (intIndex == -1)     Console.WriteLine("\t" + "Row not found!"); else     Console.WriteLine("\t" + vue[intIndex]["CompanyName"]); Console.WriteLine(); Console.WriteLine("Use the FindRows method to locate rows " +                   "based on the Country column"); vue.Sort = "Country"; DataRowView[] aRows = vue.FindRows("Spain"); if (aRows.Length == 0)     Console.WriteLine("\t" + "No rows found!"); else     foreach (DataRowView row in aRows)         Console.WriteLine("\t" + row["City"]);

GetEnumerator Method

The GetEnumerator method offers another way to view the contents of a DataView. It returns an instance of an IEnumerator object, which resides in the System.Collections namespace.

You use the IEnumerator object's MoveNext method the same way that you use the DataReader object's Read method. MoveNext returns a Boolean value that indicates whether another object in the collection is available. The Current property returns the currently available object using the generic Object data type. The following code snippet converts the output to a DataRowView object:

Visual Basic .NET

Dim tbl As New DataTable("Customers")  Dim vue As DataView(tbl) Dim row As DataRowView Dim objEnum As IEnumerator = vue.GetEnumerator Do While objEnum.MoveNext()     row = CType(objEnum.Current, DataRowView)     Console.WriteLine(row("CompanyName")) Loop

Visual C# .NET

DataTable tbl = new DataTable("Customers");  DataView vue = new DataView(tbl); DataRowView row; IEnumerator objEnum = vue.GetEnumerator(); while (objEnum.MoveNext()) {     row = (DataRowView) objEnum.Current;      Console.WriteLine(row["CompanyName"]); }

The ListChanged Event of the DataView Object

The DataView object has one event, ListEvent, which fires when the contents of the DataView change—such as when a row visible through the DataView is added, deleted, or modified; when a DataAdapter fills the underlying DataTable; or when the DataView object's RowFilter, RowStateFilter, Sort, or Table property changes. Here's one example:

Visual Basic .NET

Dim vue As New DataView() AddHandler vue.ListChanged, vue_ListChanged Private Sub vue_ListChanged(ByVal sender As Object, _                             ByVal e As ListChangedEventArgs)     Console.WriteLine("ListChanged - " & _                       e.ListChangedType.ToString()) End Sub

Visual C# .NET

//Assumes using System.ComponentModel DataView vue = new DataView; vue.ListChanged += new ListChangedEventHandler(vue_ListChanged);   private void vue_ListChanged(object sender, ListChangedEventArgs e) {     Console.WriteLine("ListChanged - " +                        e.ListChangedType.ToString()); }

Properties of the DataRowView Object

Most of the properties of the DataRowView object are read-only. Table 8-4 summarizes the properties.

Table 8-4 Properties of the DataRowView Object

Property

Data Type

Description

DataView

DataView

Returns the DataView to which the DataRowView belongs (read-only)

IsEdit

Boolean

Indicates whether the row is currently being modified (read-only)

IsNew

Boolean

Indicates whether the row is a new pending row (read-only)

Item

Object

Sets or returns the contents of a column

Row

DataRow

Returns the corresponding DataRow object for the DataRowView (read-only)

RowVersion

DataRowVersion

Returns the RowVersion of the corresponding DataRow that is visible via the DataViewRow (read-only)

DataView Property

The DataView property returns the DataView to which the DataRowView object belongs.

IsEdit and IsNew Properties

You can use the IsEdit and IsNew properties to determine whether the DataRowView object is currently being edited and what type of edit is being made.

If you're in the process of editing a new row (you've created the new DataRowView using DataView.AddNew but haven't called EndEdit to add the row to the underlying DataTable), IsNew will return True and IsEdit will return False. If you're editing a row that already exists in the table, IsEdit will return True and IsNew will return False.

Item Property

The DataRowView object's Item property offers much of the same functionality as the DataRow object's Item property. You can use the DataRowView object's Item property to modify or examine the contents of a column of data for that row. You can access the column by using its name or its ordinal value in the Item property.

Row Property

The DataRowView object doesn't offer all of the functionality available through the DataRow object. For example, the DataRowView object doesn't expose methods such as AcceptChanges and GetChanges. If you need to work with features of the DataRow interface, you can use the DataRowView object's Row property. This property returns the DataRow object that corresponds to the DataRowView object.

RowVersion Property

If you're working with a row of data using the DataRowView interface and you want to determine which version of the data you're seeing through the Item property, you can check the RowVersion property of the DataRowView.

The RowVersion property is read-only and returns a value from the DataRowVersion enumeration.

Methods of the DataRowView Object

Table 8-5 summarizes the methods that the DataRowView object exposes.

Table 8-5 Methods of the DataRowView Object

Method

Description

BeginEdit

Begins the process of editing the row

CancelEdit

Cancels pending changes for the row

CreateChildView

Creates a new DataView containing only the child rows for the current row

Delete

Marks the row as deleted

EndEdit

Saves pending changes for the row

BeginEdit, CancelEdit, and EndEdit Methods

The BeginEdit, CancelEdit, and EndEdit methods of the DataRowView object work the same way as the corresponding methods of the DataRow object. If you call the BeginEdit method before modifying the row, your changes will not be committed to the row until you call EndEdit. If you want to discard the changes instead, you can call CancelEdit.

CreateChildView Method

Let's say you want to create a DataView object that displays only the related child rows for a particular row. If you're working with the customers and orders relation we've used throughout this book, setting up the new DataView is simple. You set the Table property to the orders DataTable and then set the RowFilter property to a string such as CustomerID = 'ALFKI'.

That sounds very straightforward. But what if you also need to check the column value (CustomerID) for delimiters? Or what if you're working with a relationship that's based on a combination of columns?

The DataRowView object offers a simpler and more elegant solution—using the CreateChildView method. You can call this method and supply either a relation name or a DataRelation object (just as the GetChildRows method on the DataRow object). The CreateChildView method will return a new DataView object that uses that relation as its filter.

The following code snippet shows how to use the CreateChildView method:

Visual Basic .NET

Dim ds As New DataSet() Dim tblCustomers, tblOrders As DataTable  tblCustomers = ds.Tables("Customers") tblOrders = ds.Tables("Orders") ds.Relations.Add("CustomersOrders", tblCustomers.Columns("CustomerID"), _                  tblOrders.Columns("CustomerID")) Dim vueCustomers, vueOrders As DataView vueCustomers = New DataView(tblCustomers) vueOrders = vueCustomers(0).CreateChildView("CustomersOrders")

Visual C# .NET

DataSet ds = new DataSet(); DataTable tblCustomers, tblOrders;  tblCustomers = ds.Tables["Customers"]; tblOrders = ds.Tables["Orders"]; ds.Relations.Add("CustomersOrders", tblCustomers.Columns["CustomerID"],                   tblOrders.Columns["CustomerID"]); DataView vueCustomers, vueOrders; vueCustomers = new DataView(tblCustomers); vueOrders = vueCustomers[0].CreateChildView("CustomersOrders"); 

note

When you use the CreateChildView method to create a new DataView, the RowFilter property will return an empty string. However, only the expected child rows will be visible. How is this possible? Well, the new DataView object uses a feature that technical people like to refer to as "magic."

Delete Method

You can use the DataRowView object's Delete method to delete a row. Remember that the row will still exist in the DataTable and will be marked as deleted. The row will not actually be removed from the DataTable until you call AcceptChanges or submit the pending deletion to your database using a DataAdapter.



Microsoft ADO. NET Core Reference
Microsoft ADO.NET (Core Reference) (PRO-Developer)
ISBN: 0735614237
EAN: 2147483647
Year: 2002
Pages: 104
Authors: David Sceppa

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net