.Net DataView and DataTable Binding

I have a simple Windows Forms Application that binds a DataView to a ListBox. This DataView uses Linq to sort my DataTable by a single column, descending. My ListBox is then bound to a DataView. Then I have a simple form to add data to the DataTable. When I add the DataRow to the DataTable, it shows up in the ListBox.

I'm curious about what's going on behind the scenes ... I've read :

A DataView is a customized view of a single data table that can be filtered or sorted. Data View is data "snapshot" used by sophisticated management. You can simple or complex data binding within the data, but remember that you are binding to a fixed "picture" of the data, not a clean, updated data source.

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

+2


source to share


1 answer


DataView

is not a snapshot. It updates automatically and immediately after changing the baseline DataTable

. New lines added to DataTable

that match the filter criteria DataView

will automatically appear in DataView

. Likewise, lines deleted from DataTable

will automatically disappear from DataView

.

The following is dynamic in nature 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 the DataView fire an event to update when the underlying DataTable changes?

It's an internal implementation detail, but it's plausible that it uses events.

Note that you can use the DataTable.Copy

copy method DataTable

if you really want to take a snapshot DataTable

.

+2


source







All Articles