10.19. Automatically Refreshing a DataTable Periodically

Problem

You need to automatically refresh a DataSet periodically.

Solution

Use extended properties and a timer.

The solution uses a table named AutoRefresh in the database AdoDotNet35Cookbook. The following T-SQL statement creates the table:

	USE AdoDotNet35Cookbook
	GO

	CREATE TABLE AutoRefresh(
	    Id int NOT NULL PRIMARY KEY,
	    Field1 nvarchar(50) NULL,
	    Field2 nvarchar(50) NULL )

Add three records to the AutoRefresh table by executing the following T-SQL batch:

	USE AdoDotNet35Cookbook
	GO

	INSERT INTO AutoRefresh VALUES (1, 'Field1.1', 'Field2.1');
	INSERT INTO AutoRefresh VALUES (2, 'Field1.2', 'Field2.2');
	INSERT INTO AutoRefresh VALUES (3, 'Field1.3', 'Field2.3');

The solution creates a DataTable containing the schema and all records from the AutoRefresh table in the AdoDotNet35Cookbook database. A timer is set up to check whether the data needs to be refreshed based on the refresh time (every 15 seconds) stored in the ExtendedProperty of the DataTable. The data is refreshed if required, the ExtendedProperty updated to reflect the next refresh time, and the new data output to the console. A second timer is used to update the data in the data source after 10 seconds. The first refresh of the data after 15 seconds shows the updated data.

The C# code in Program.cs in the project AutoRefreshDataTable is shown in Example 10-31.

Example 10-31. File: Program.cs for AutoRefreshDataTable solution

using System; using System.Data; using System.Data.SqlClient; ...

Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.