Using ADO.NET Design-Time Features in Classes Without a GUI

Problem

The design-time environment provides controls and wizards to facilitate creation of and management of properties of ADO.NET objects. You want to use that design-time functionality when creating classes that do not have a GUI.

Solution

Create a component and use its design-time functionality.

The solution contains two parts : the component and the test container for the component. To create the component Component0717.cs , add two controls to its design surface:

The sample code for the component exposes one property and one method:

MyDataTable

A read-only property that returns a DataTable filled using the SqlDataAdapter control.

Update( )

This method takes a DataTable object argument that uses the SqlDataAdapter control to update changes to the DataTable (retrieved using the MyDataTable property of the component) back to the database.

The C# code for the component is shown in Example 7-33.

Example 7-33. File: Component0717.cs

// Namespaces, variables, and constants using System; using System.Data; using System.Data.SqlClient; // . . . public DataTable MyDataTable { get { // Fill a table using the DataAdapter control. DataTable dt = new DataTable( ); da.Fill(dt); return dt; } } public void Update(DataTable dt) { // Update the table back to the data source. da.Update(dt); }

The test container sample code contains two event handlers:

Form.Load

Instantiates the component Component0717 and binds the default view of the DataTable that it exposes (through the MyDataTable property) to the DataGrid on the form.

Update Button.Click

Instantiates the component Component0717 and calls the Update( ) method of the component to update changes made in the DataGrid to the DataTable retrieved in the Form.Load event handler.

The C# code for the test container is shown in Example 7-34.

Example 7-34. File: UsingDesignTimeFeauresWithComponentsForm.cs

// Namespaces, variables, and constants using System; using System.Data; // . . . private void UsingDesignTimeFeauresWithComponentsForm_Load(object sender, System.EventArgs e) { // Bind the default of the table from the component to the grid. Component0717 c = new Component0717( ); dataGrid.DataSource = c.MyDataTable.DefaultView; } private void updateButton_Click(object sender, System.EventArgs e) { // Update the table to the data source using the component. Component0717 c = new Component0717( ); c.Update(((DataView)dataGrid.DataSource).Table); }

Discussion

The component and control are special-purpose classes in the .NET Framework:

To create a component, simply right-click on a project or folder in the Solution Explorer window and select Add Add Component. The View Designer button in the Solution Explorer window accesses the design surface of the component.

Working with XML

Категории