views:

320

answers:

1

I have a simple Windows Forms application which binds a DataView to a ListBox. This DataView uses Linq to sort my DataTable by a specific column descending. My ListBox is then bound to the DataView. I then have a simple form to add data to the DataTable. When I add a DataRow to the DataTable it displays in the ListBox.

I'm curious as to whats going on behind the scenes... I've read:

A DataView object is a customized view of a single data table that may be filtered or sorted. A data view is the data "snapshot" used by complex-bound controls. You can simple- or complex-bind to the data within a data view, but be aware that you are binding to a fixed "picture" of the data rather than a clean, updating data source.

I would have thought that since the DataView is a "snapshot" it wouldn't have automatically updated. Does a DataView add an event to update when the underlying DataTable is modified? Don't get me wrong, this is how I want it to work, but is this always the case?

+1  A: 

The DataView is not a snapshot. It is updated automatically and immediately as the underlying DataTable changes. New rows added to the DataTable that meet the DataView's filter criteria will automatically appear in the DataView. Similarly, rows removed from the DataTable will automatically disappear from the DataView.

The following illustrates the dynamic nature of the DataView even when using LINQ:

using System;
using System.Linq;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FirstName");

            var query = from row in dt.AsEnumerable()
                        where row.Field<string>("FirstName").StartsWith("S")
                        select row;

            DataView view = query.AsDataView();

            Console.WriteLine(view.Count); // Prints 0
            dt.Rows.Add("Sam");
            dt.Rows.Add("John");
            Console.WriteLine(view.Count); // Prints 1
            dt.Rows.Add("Sally");
            dt.Rows.Add("Mary");
            Console.WriteLine(view.Count); // Prints 2
            dt.Rows.RemoveAt(0);
            Console.WriteLine(view.Count); // Prints 1
        }
    }
}

Does a DataView add an event to update when the underlying DataTable is modified?

This is an internal implementation detail, but it is plausible that this uses events.

Note that you can use the DataTable.Copy method to copy a DataTable, if you really want to create a snapshot of the DataTable.

binarycoder