Disconnected Operations Part II: DataView, XML, and Strongly Typed DataSets
- A View to a DataSet
- Parsing XML with the DataSet
- The Strongly Typed DataSet
- Conclusion
Learn the advanced features of disconnected operations in ADO.NET including the sortable/filterable DataView, the XML parsing capabilities of the DataSet, as well as the strong-typed DataSet and how they contribute to the data access stack of .NET.
Dale Michalk is an application development consultant for Microsoft Premier Support in Charlotte, NC. He is a regular contributor to InformIT on new technology topics such as .NET and XML.
The disconnected capabilities of ADO.NET provide rich functionality beyond the basic necessities of loading and storing information to and from a data source. ADO.NET has the flexibility to work with XML natively via the DataSet, create a dynamic viewing object called the DataView that filters and sorts a DataTable, and build a strongly typed DataSet that mimics the data domain it represents. This article discusses each of these useful features and what they contribute to the data access stack of .NET.
NOTE
Click here to download a zip file containing the source files for this article.
A View to a DataSet
The DataView provides a changeable, dynamic view into the world of data inside a DataSet. It's commonly used with data-binding scenarios and GUI controls to provide a different look at the same collection of data for analysis by the end user of a program. It has sorting and filtering capabilities as well as supporting editing with the appropriate property configuration that can synchronize its efforts with the single DataTable that it's mapped to.
A DataView can be created through direct instantiation by passing a DataTable reference to its constructor or by setting the DataTable property of a newly minted DataView. The DataTable has a factory property called DefaultView that generates a default DataView on the DataTable. The construction patterns reinforce the fact that a DataView can only reference a single DataTable of the DataSet at a time. The code in Listing 1 shows the various creation options.
Listing 1Creating the DataView
DataTable dt = GetLoadedDataTableFromSomewhere(); // create a DataView by passing DataTable to the constructor DataView dv1 = new DataView(dt); // create a DataView by setting the DataTable property DataTable dv2 = new DataTable(); // create a DataView by using DataTable DefaultView property DataTable dv3 = dt.DefaultView;
Once the DataView is created, you can set the sorting and filtering through the Sort, RowFilter, and RowStateFilter properties. The Sort property takes a string containing the name of the DataColumn or DataColumns, separated by commas, and the sort type in the form of ASC (ascending) or DESC (descending), with the default sort being ascending.
The RowFilter property takes a more complex string expression that consists of an optionally repeating DataColumn name, an operator, and the value to apply using the operator. The set of operators spans those familiar to SQL programming: comparison operators (such as <, >, =); a string-matching operator in the form of LIKE and the % and * wildcards; as well as logical operators including OR and AND to compose expressions. See the documentation for the Expression class for more complete details on the exact operators and values supported.
The final filtering property of interest in the DataView is the RowStateFilter. This allows the programmer to view rows that meet state criteria depending on the DataViewRowState enumeration. The state changes as a result of data modification through row data changes, row additions, and row deletions. In Listing 2, this enumeration takes on the values listed in Table 1.
Table 1 DataViewRowState Enumeration Values
Value |
Description |
Added |
New rows added |
CurrentRows |
All rows including unchanged, new, and modified rows |
Deleted |
Rows deleted from the DataTable |
ModifiedCurrent |
A current version, which is a modified version of original data |
ModifiedOriginal |
The original version, although it has since been modified |
None |
None of the rows |
OriginalRows |
All of the original rows, including unchanged and deleted rows |
Unchanged |
Rows that haven't changed |
In addition to being a viewing tool, the DataView can act as an input tool. The AllowEdit, AllowNew, and AllowDelete properties control whether a row can be modified, added, or deleted to the DataView and its related DataTable. AllowNew affects the use of the DataView AddRow method, AllowDelete affects the Delete method, and AllowEdit determines whether the DataRowView object modeling the row of data can be modified.
With DataView preliminaries out of the way, we can discuss a working implementation of the process. I've departed from the console applications of the previous articles to use a .NET Windows forms application and its rich set of controls. The DataGrid class in particular makes it easy to see the results of our manipulation of a DataView and happily binds to either the DataTable or DataView. Listing 2 shows the code for the ViewDataSet form class. Listing 3 shows database utility code to pull data from Northwind for the demos in this article.
Listing 2ViewDataSet.cs Code Listing for DataView
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; using System.Windows.Forms.Design; namespace DisconnectedOpsIIDemo { /// <summary> /// Summary description for ViewDataSet. /// </summary> public class ViewDataSet : System.Windows.Forms.Form { [STAThread] static void Main(string[] args) { Application.Run(new ViewDataSet()); } private DataSet CustDS; private System.Windows.Forms.Button btnView; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtFilter; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtSort; private System.Windows.Forms.Label label3; private System.Windows.Forms.DataGrid ViewDataGrid; private System.Windows.Forms.DataGrid MainDataGrid; private System.Windows.Forms.ComboBox cboRowState; private System.Windows.Forms.CheckBox chkChanges; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public ViewDataSet() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after // InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - /// do not modify /// the contents of this method with the code /// editor. /// </summary> private void InitializeComponent() { this.btnView = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.txtFilter = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.txtSort = new System.Windows.Forms.TextBox(); this.ViewDataGrid = new System.Windows.Forms.DataGrid(); this.label3 = new System.Windows.Forms.Label(); this.MainDataGrid = new System.Windows.Forms.DataGrid(); this.cboRowState = new System.Windows.Forms.ComboBox(); this.chkChanges = new System.Windows.Forms.CheckBox(); ((System.ComponentModel.ISupportInitialize) (this.ViewDataGrid)).BeginInit(); ((System.ComponentModel.ISupportInitialize) (this.MainDataGrid)).BeginInit(); this.SuspendLayout(); // // btnView // this.btnView.Location = new System.Drawing.Point(480, 376); this.btnView.Name = "btnView"; this.btnView.Size = new System.Drawing.Size(136, 23); this.btnView.TabIndex = 10; this.btnView.Text = "Refresh View"; this.btnView.Click += new System.EventHandler(this.btnView_Click); // // label2 // this.label2.Location = new System.Drawing.Point(448, 216); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(48, 16); this.label2.TabIndex = 9; this.label2.Text = "Filter"; // // txtFilter // this.txtFilter.Location = new System.Drawing.Point(448, 232); this.txtFilter.Multiline = true; this.txtFilter.Name = "txtFilter"; this.txtFilter.Size = new System.Drawing.Size(168, 48); this.txtFilter.TabIndex = 8; this.txtFilter.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(448, 176); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(48, 16); this.label1.TabIndex = 7; this.label1.Text = "Sort"; // // txtSort // this.txtSort.Location = new System.Drawing.Point(448, 192); this.txtSort.Name = "txtSort"; this.txtSort.Size = new System.Drawing.Size(168, 20); this.txtSort.TabIndex = 5; this.txtSort.Text = ""; // // ViewDataGrid // this.ViewDataGrid.DataMember = ""; this.ViewDataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.ViewDataGrid.Location = new System.Drawing.Point(8, 176); this.ViewDataGrid.Name = "ViewDataGrid"; this.ViewDataGrid.Size = new System.Drawing.Size(432, 224); this.ViewDataGrid.TabIndex = 6; // // label3 // this.label3.Location = new System.Drawing.Point(448, 288); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(64, 16); this.label3.TabIndex = 12; this.label3.Text = "RowState"; // // MainDataGrid // this.MainDataGrid.DataMember = ""; this.MainDataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.MainDataGrid.Location = new System.Drawing.Point(8, 8); this.MainDataGrid.Name = "MainDataGrid"; this.MainDataGrid.Size = new System.Drawing.Size(608, 152); this.MainDataGrid.TabIndex = 13; // // cboRowState // this.cboRowState.Items.AddRange( new object[] { "Added", "CurrentRows", "Deleted", "ModifiedCurrent", "ModifiedOriginal", "None", "OriginalRows", "Unchanged"}); this.cboRowState.Location = new System.Drawing.Point(448, 312); this.cboRowState.Name = "cboRowState"; this.cboRowState.Size = new System.Drawing.Size(168, 21); this.cboRowState.TabIndex = 15; this.cboRowState.Text = "CurrentRows"; // // chkChanges // this.chkChanges.Location = new System.Drawing.Point(448, 344); this.chkChanges.Name = "chkChanges"; this.chkChanges.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkChanges.Size = new System.Drawing.Size(128, 24); this.chkChanges.TabIndex = 17; this.chkChanges.Text = "Allow Changes"; // // ViewDataSet // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(624, 413); this.Controls.AddRange( new System.Windows.Forms.Control[] { this.chkChanges, this.cboRowState, this.MainDataGrid, this.label3, this.btnView, this.label2, this.txtFilter, this.label1, this.txtSort, this.ViewDataGrid}); this.Name = "ViewDataSet"; this.Text = "ViewDataSet"; this.Load += new System.EventHandler(this.ViewDataSet_Load); ((System.ComponentModel.ISupportInitialize) (this.ViewDataGrid)).EndInit(); ((System.ComponentModel.ISupportInitialize) (this.MainDataGrid)).EndInit(); this.ResumeLayout(false); } #endregion private void btnView_Click(object sender, System.EventArgs e) { DataView dv = new DataView(CustDS.Tables["Customers"]); dv.Sort = txtSort.Text; dv.RowFilter = txtFilter.Text; dv.RowStateFilter = (DataViewRowState) Enum.Parse(typeof(DataViewRowState), cboRowState.SelectedItem.ToString(), true); ViewDataGrid.DataSource = dv; if (chkChanges.Checked == true) { dv.AllowDelete = true; dv.AllowEdit = true; dv.AllowNew = true; } else { dv.AllowDelete = false; dv.AllowEdit = false; dv.AllowNew = false; } } private void ViewDataSet_Load(object sender, System.EventArgs e) { CustDS = new DataSet(); DataAdapterUtility.LoadCustomers(CustDS); MainDataGrid.DataSource = CustDS.Tables["Customers"].DefaultView; } } }
Listing 3DataAdapterUtility.cs Code for Loading DataSet from the Northwind Customer Table
using System; using System; using System.Data; using System.Data.SqlClient; namespace DisconnectedOpsIIDemo { public class DataAdapterUtility { public static void LoadCustomers(DataSet ds) { SqlConnection conn = new SqlConnection("server=(local);" + "database=Northwind;integrated security=true;"); conn.Open(); SqlCommand cmdSelect = new SqlCommand("SELECT CustomerID, " + " CompanyName,ContactName, ContactTitle, " + " Address, City, Region, PostalCode, " + " Country, Phone, Fax " + " FROM Customers"); cmdSelect.Connection = conn; SqlDataAdapter daCusts = new SqlDataAdapter(); daCusts.SelectCommand = cmdSelect; daCusts.Fill(ds,"Customers"); } public static void LoadOrders(DataSet ds) { SqlConnection conn = new SqlConnection("server=(local);" + "database=Northwind;integrated security=true;"); conn.Open(); SqlCommand cmdSelect = new SqlCommand("SELECT OrderID, CustomerID, " + "EmployeeID, OrderDate, RequiredDate, " + "ShippedDate, ShipVia, Freight," + "ShipName, ShipAddress, ShipCity, " + "ShipRegion, ShipPostalCode, " + "ShipCountry FROM Orders"); cmdSelect.Connection = conn; SqlDataAdapter daCusts = new SqlDataAdapter(); daCusts.SelectCommand = cmdSelect; daCusts.Fill(ds,"Orders"); } public static void LinkCustOrders(DataSet ds) { DataRelation dr = new DataRelation("CustOrders", ds.Tables["Customers"].Columns["CustomerID"], ds.Tables["Orders"].Columns["CustomerID"], true); dr.Nested = true; ds.Relations.Add(dr); } } }
The ViewDataSet forms class has a private member DataSet named CustDS that stores the data loaded in from the Customers table in the SQL Server Northwind sample database. The load event of the form uses the DataAdapterUtility class from Listing 3 to fill the data into the CustDS DataSet. After the data load, the DataTable representing the customers is bound to the MainDataGrid DataGrid control via the DataView construction property named DefaultView, as shown in Figure 1. The DataGrid control has the ability to sort, update, delete, and add rows to the DataSet to which it's bound.
Figure 1 Loading DataGrid with DataSet from the Northwind Customers table.
The bottom portion of the form in Figure 1 is used to demonstrate the DataView capabilities. The ViewDataGrid member of the ViewDataSet form is a DataGrid control that's bound to a custom-constructed DataView object created when the RefreshView button is clicked. A set of text box controls provides input for the Sort and RowFilter expressions, while the combo box represents the RowStateFilter enumeration values. The Allow Changes check box is linked to the AllowEdit, AllowDelete, and AllowNew properties of the DataView and sets all of them to true or false by virtue of the check box value. The DataGrid control is smart enough to read the changes in these values and react to user input accordingly.
Figure 2 shows the result of sorting the DataView using Country and then Address as the columns in the Sort property. The filter expression then does a LIKE operation for all customers with a name that starts with B. Figure 3 shows the option for adding a row that becomes available when the Allow Changes check box is checked. We added the row with BALLY as the customer ID. (You have to scroll down to the bottom of the MainDataGrid control to see the BALLY row.) Figure 4 shows the results of deleting the customer with the customer ID value of BERGS, and how the changes are propagated to both DataGrid controls.
Figure 2 Sorting using Country and Address while using LIKE and Customers starting with B.
Figure 3 Adding a new row when the AllowNew property is true.
Figure 4 Result of deleting a BERGS row when the AllowNew property is true and changes are propagated to both DataGrid controls.