Creating and Using Strongly Typed DataSet Objects



Creating and Using Strongly Typed DataSet Objects

Create and manipulate DataSets: Create a strongly typed DataSet.

The best way to understand strongly typed DataSet objects is to see what you can do with one syntactically. Suppose you have a normal DataSet object, and you've extracted a DataTable object named dt from this DataSet object. Then you can refer to a value in the DataTable object with any of these syntaxes:


dt.Rows[0][0]

dt.Rows[0]["ColumnName"]

All these syntaxes have one thing in common: They're all late-bound. That is, .NET doesn't know until runtime that ColumnName is a valid column name in the DataTable. By contrast, in a strongly typed DataSet, the columns actually become properties of the row. With a strongly typed DataSet, an early-bound version of the data-retrieval code becomes available:


dt.Rows[0].ColumnName

In addition to being faster than the late-bound syntax, this syntax also has the benefit that column and table names show up in the applicable IntelliSense lists.

In this section, you'll learn two different ways to create strongly typed DataSet objects. After that, I'll show you how to use a strongly typed DataSet in code.

Using the Component Designer to Create a Strongly Typed DataSet Object

One way to create a strongly typed DataSet object is to derive it directly from a table or other data-bearing object in a database. Step-by-Step 1.10 demonstrates this technique.

STEP BY STEP

1.10 Creating a Strongly Typed DataSet with the Component Designer

  1. In Solution Explorer, right-click the project and select Add, Add Windows Form from the context menu. This opens the Add New Item dialog box. Name the form StepByStep1_10.cs and click Open.

  2. Expand the Server Explorer tree view to show the Data Connection node. Drill into the Tables folder within the Northwind sample database.

  3. Drag the Employees table from Server Explorer and drop it on the form. This adds a SqlConnection object named sqlConnection1 and a SqlDataAdapter object named sqlDataAdapter1 to the component tray of the form, as shown in Figure.

    16. You can create ADO.NET objects by dragging and dropping tables and other data elements from the Server Explorer.

    graphics/01fig16.jpg

  4. Select the SqlDataAdapter object. Click the Generate DataSet hyperlink at the bottom of the Properties window, as shown in Figure.

    Figure. You can generate a DataSet object by clicking the Generate DataSet hyperlink in the Properties window for a SqlDataAdapter object.

    graphics/01fig17.jpg

  5. Clicking the hyperlink opens the Generate DataSet dialog box, as shown in Figure. Name the new DataSet object dsEmployees and select the check box to add the DataSet to the DataSet schema designer. Click OK.

    Figure. The Generate DataSet dialog box enables you to create new DataSet objects.

    graphics/01fig18.jpg

  6. You'll see a new object, dsEmployees.xsd, appear in the Solution Explorer. This is a DataSet schema file that describes the new strongly typed DataSet object. Click the Show All Files button on the Solution Explorer toolbar. Expand the dsEmployees.xsd node to see the dsEmployees.cs file, as shown in Figure. This is a class file that can be instantiated to produce the strongly typed DataSet object.

    Figure. The dsEmployees.cs file contains the source code for the strongly typed DataSet.

    graphics/01fig19.jpg

In addition to the new objects in Solution Explorer, this example also adds a new component, dsEmployees1, to the component tray underneath the form. This is an instance of the class defined in dsEmployees.cs. If you inspect the code behind the form, you can find the declaration for the new component:


private _320C01.dsEmployees dsEmployees1;

Creating a Strongly Typed DataSet from a DataSet Schema

You can also create a strongly typed DataSet from a DataSet schema file. More precisely, if you've created a DataSet schema in your Visual C# .NET project, Visual C# .NET automatically creates a strongly typed DataSet class that matches the structure defined in the schema. As you edit the schema, Visual C# .NET keeps the DataSet class synchronized with your edits.

WARNING

Naming a Strongly Typed DataSet Object You should not name the DataSet schema file dsCustomers.xsd with the name of its enclosing tables—that is, Customers.xsd or Orders.xsd. The corresponding code file (that is, the .cs file) created for this DataSet object contains properties to provide access to their enclosing members—that is, Customers or Orders. If you named a class with the same name as its enclosing table, you would get the error Member names cannot be the same as their enclosing type.


If you've been following along with the Step-by-Steps in this chapter, take a look at the files in Solution Explorer. If you click the Show All Files toolbar button, you'll find two files as children of the dsCustomers.xsd DataSet schema file:

  • dsCustomers.cs— This file is the class definition for a strongly typed DataSet based on the DataSet schema that you've been working with.

  • dsCustomers.xsx— This file contains information on the layout of objects within the DataSet schema designer window.

Using a Strongly Typed DataSet Object

Now that you've built a strongly typed DataSet object, what can you do with it? Step-by-Step 1.11 demonstrates the syntax for using such a DataSet object.

STEP BY STEP

1.11 Using a Strongly Typed DataSet Object

  1. Open the form StepByStep1_10.cs that you created in Step by Step 1.10 in the DataSet schema designer. Add a new ListBox control to the form, and name the control lbEmployees.

  2. Double-click on the form to open the event handler for the form's Load event. Add this code to handle the Load event:

    
    private void StepByStep1_10_Load(object sender,
    
        System.EventArgs e)
    
    {
    
        sqlDataAdapter1.Fill(dsEmployees1, "Employees");
    
        foreach(dsEmployees.EmployeesRow EmpRow
    
                    in dsEmployees1.Employees)
    
        {
    
            lbEmployees.Items.Add(
    
                EmpRow.FirstName + " " + EmpRow.LastName);
    
        }
    
    }
    
    

    Notice as you type this code that the IntelliSense feature fills in the names of tables and columns for you.

  3. Insert the Main() method to launch the form as follows:

    
    [STAThread]
    
    static void Main()
    
    {
    
        Application.Run(new StepByStep1_10());
    
    }
    
    
  4. Modify the properties of project 320C01 to set the form StepByStep1_10 as the startup object for the project. Run the project. You'll see a list of employees on the form, as shown in Figure.

    Figure. You can perform early binding with data objects with the help of a strongly typed DataSet object.

    graphics/01fig20.jpg

A strongly typed DataSet class inherits from the base DataSet class, so it has all the methods and properties of the DataSet. The strong typing gives you the benefits of design-time IntelliSense and type checking. It also makes your code easier to read. Given the ease with which Visual Studio .NET can create strongly typed DataSet classes, you should plan to use them whenever possible.

REVIEW BREAK

  • A strongly typed DataSet object brings the benefits of early binding to your data access code.

  • You can create a strongly typed DataSet object by using the component designer with components dragged from Server Explorer, or by building a DataSet schema file.

  • When you're working with a strongly typed DataSet object in code, IntelliSense will show you the names of the tables and columns contained within the DataSet object.