Home > Articles > Programming > Windows Programming

Disconnected Operations Part II: DataView, XML, and Strongly Typed DataSets

Learn the advanced features of disconnected operations in ADO.NET, including the sortable/filterable DataView, the XML parsing capabilities of the DataSet, and the strongly 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.

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 1—Creating 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 2—ViewDataSet.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 3—DataAdapterUtility.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 1Figure 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 2Figure 2 Sorting using Country and Address while using LIKE and Customers starting with B.

Figure 3Figure 3 Adding a new row when the AllowNew property is true.

Figure 4Figure 4 Result of deleting a BERGS row when the AllowNew property is true and changes are propagated to both DataGrid controls.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020